ios - 以编程方式将 subview 添加到 NIB 的方法

标签 ios objective-c uiview drawrect

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

-(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 ,它表示每当修改 View 框架时都会调用 drawRect 。我应该使用什么方法添加自定义 UI 元素,或者应该创建自己的方法并调用它。

最佳答案

一般我都是这样

-(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 .
}

关于ios - 以编程方式将 subview 添加到 NIB 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40699892/

相关文章:

iphone - 检查对象是否为 NSInteger

ios - 未找到架构 x86_64 的符号 - iOS

iphone - 如何在纵向模式应用程序中滑入 UIView?

ios - 将约束应用于 Facebook 登录按钮

iphone - 对象在 iOS 5 ARC 中发布得太早

ios - 为什么我的单元格在我的 UITableView 中显示为空白?

iOS 删除键没有反应

ios - 波形颜色变化的动画图像删除

ios - 无法运行使用iOS SDK 4.3编译的iOS 3.X应用

ios - 这两种声明样式之间的区别/优点是什么