【问题标题】:What method to programmatically add subview to NIB什么方法以编程方式将子视图添加到 NIB
【发布时间】:2016-11-20 01:56:36
【问题描述】:

我现在正在将UIButton 添加到drawRect 中的UIView 笔尖。

-(void)drawRect:(CGRect)rect {
     self.button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
     [self.button setImage:[UIImage imageNamed:@"buttonImage.png"] forState:UIControlStateNormal];
     [self.button setTintColor:[UIColor whiteColor]];
     [self addSubview:self.button];
}

阅读此post 后,它说每当修改视图框架时都会调用drawRect。我应该添加什么方法来添加我的自定义 UI 元素,或者我应该创建自己的方法并调用它。

【问题讨论】:

  • 覆盖 initWithFrameinitWithCoder。调用一个方法在其中添加您的按钮。

标签: ios objective-c uiview drawrect


【解决方案1】:

我通常是这样的

-(instancetype)initWithCoder:(NSCoder *)aDecoder{

    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self load] ;
    }
    return self ;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame] ;
    if(self)
    {
       [self load] ;
    }
    return self ;
}
-(void)load{
    //add your subviews here .
}

【讨论】:

    猜你喜欢
    • 2016-07-27
    • 1970-01-01
    • 2017-10-09
    • 2017-06-28
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多