ios自定义一个view怎么使用

2025-03-03 04:22:05
推荐回答(1个)
回答1:

  1. 先来新建一个自定义的View,继承自UIView


  2. 新建一个xib文件

    在这里,为了更好地识别,我们把这个xib的名字命名成我们之前新建的那个view子类。


  3. 更改xib的File's Owner class,指向我们创建好的class


  4. 为xib中已存在的view绑定IBOutlet,命名为contentView。类比tableview cell中content view的作用。


  5. 在CustomView.m中实现加载Content View

    - (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
         self = [super initWithCoder:aDecoder];

         if (self) {
             [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
             self.contentView.frame = self.bounds;
             [self addSubview:self.contentView];
         }

         return self;
     }
  6. 在Content View中任意地添加子view,添加约束,愉快地玩耍吧~