自定义控件

步骤

  1. 新建一个继承UIView的类
  2. 重写init方法,在init方法中添加子控件
  3. 在layoutSubviews方法中设置子控件的frame(layoutSubviewsy一定要调用super )
  4. 提供一个模型属性,重写模型属性的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
复制代码

 

posted @   千面客  阅读(112)  评论(0编辑  收藏  举报
编辑推荐:
· Brainfly: 用 C# 类型系统构建 Brainfuck 编译器
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
阅读排行:
· DeepSeek 全面指南,95% 的人都不知道的9个技巧(建议收藏)
· Tinyfox 发生重大改版
· 对比使用DeepSeek与文新一言,了解DeepSeek的关键技术论文
· Brainfly: 用 C# 类型系统构建 Brainfuck 编译器
· DeepSeekV3+Roo Code,智能编码好助手
点击右上角即可分享
微信分享提示