步骤
- 新建一个继承UIView的类
- 重写init方法,在init方法中添加子控件
- 在layoutSubviews方法中设置子控件的frame(layoutSubviewsy一定要调用super )
- 提供一个模型属性,重写模型属性的set方法(在set方法中取出模型属性,给对应的子控件赋值)
//来自文件自定义控件
#import "XMGShopView.h" #import "XMGShopModel.h" @interface XMGShopView () @property (nonatomic ,weak)UIImageView *iconImageView; @property (nonatomic ,weak)UILabel *nameLabel; @end @implementation XMGShopView // 添加子控件 // 控件的init方法内部会自动调用initWithFrame: - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // 添加图片 UIImageView *iconImageView = [[UIImageView alloc] init]; [self addSubview:iconImageView]; self.iconImageView = iconImageView; // 添加文字 UILabel *nameLabel = [[UILabel alloc] init]; nameLabel.textAlignment = NSTextAlignmentCenter; [self addSubview:nameLabel]; self.nameLabel = nameLabel; } return self; } - (instancetype)initWithShop:(XMGShopModel *)shop { if (self = [super init]) { self.shop = shop; } return self; } + (instancetype)shopViewWithShop:(XMGShopModel *)shop { XMGShopView *shopView = [[self alloc] initWithShop:shop]; return shopView; } // 布局子控件,设置子控件的位置和尺寸 - (void)layoutSubviews { // 注意点:这里一定要写 [super layoutSubviews]; CGFloat shopW = self.frame.size.width; CGFloat shopH = self.frame.size.height; self.iconImageView.frame = CGRectMake(0, 0, shopW, shopW); self.nameLabel.frame = CGRectMake(0, shopW, shopW, shopH - shopW); } // 设置子控件显示的数据 - (void)setShop:(XMGShopModel *)shop { _shop = shop; self.iconImageView.image = [UIImage imageNamed:shop.icon]; self.nameLabel.text = shop.name; } #pragma mark - 第二种设置数据的方法实现 - (void)setIcon:(NSString *)icon { self.iconImageView.image = [UIImage imageNamed:icon]; } - (void)setName:(NSString *)name { self.nameLabel.text = name; } - (void)setIcon:(NSString *)icon name:(NSString *)name; { self.iconImageView.image = [UIImage imageNamed:icon]; self.nameLabel.text = name; } @end