• 自定义控件


    步骤

    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
  • 相关阅读:
    舍不得花钱的心理分析
    DLL编程的导入导出,__declspec(dllimport),__declspec(dllexport)
    浅谈C/C++内存泄漏及其检测工具
    C++多线程编程简单实例
    linux镜像源设置
    Linux基础教程 linux无密码ssh登录设置
    兄弟连教育分享:用CSS实现鼠标悬停提示的方法
    PHP基础教程 PHP的页面缓冲处理机制
    Linux基础教程 linux下cat 命令使用详解
    PHP基础教程 php 网络上关于设计模式一些总结
  • 原文地址:https://www.cnblogs.com/wwjwb/p/12650112.html
Copyright © 2020-2023  润新知