控件的封装

封装控件的基本步骤

(1)在initWithFrame:方法中添加子控件,提供便利构造方法
(2)在layoutSubviews方法中设置子控件的frame(一定要调用super的layoutSubviews)
(3)增加模型属性,在模型属性set方法中设置数据到子控件上
.h文件

#import 

@class XMGShop;

@interface XMGShopView : UIView
/** 商品模型 */
@property (nonatomic, strong) XMGShop *shop;

+ (instancetype)shopView;
@end

.m文件

#import "XMGShopView.h"
#import "XMGShop.h"

@interface XMGShopView()
/** 图片控件 */
@property (nonatomic, strong) UIImageView *iconView;
/** 名字控件 */
@property (nonatomic, strong) UILabel *nameLabel;
@end

@implementation XMGShopView

+ (instancetype)shopView
{
    return [[self alloc] init];
}

- (UIImageView *)iconView
{
    if (_iconView == nil) {
        UIImageView *iconView = [[UIImageView alloc] init];
        iconView.backgroundColor = [UIColor blueColor];
        [self addSubview:iconView];
        _iconView = iconView;
    }
    return _iconView;
}

- (UILabel *)nameLabel
{
    if (_nameLabel == nil) {
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.font = [UIFont systemFontOfSize:11];
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.backgroundColor = [UIColor redColor];
        [self addSubview:nameLabel];
        _nameLabel = nameLabel;
    }
    return _nameLabel;
}

/**
 init方法内部会自动调用initWithFrame:方法
// */
//- (instancetype)initWithFrame:(CGRect)frame
//{
//    if (self = [super initWithFrame:frame]) {
//        self.backgroundColor = [UIColor orangeColor];
//        
//        // 添加图片
//        UIImageView *iconView = [[UIImageView alloc] init];
//        iconView.backgroundColor = [UIColor blueColor];
//        [self addSubview:iconView];
//        self.iconView = iconView;
//        
//        // 添加文字
//        UILabel *nameLabel = [[UILabel alloc] init];
//        nameLabel.font = [UIFont systemFontOfSize:11];
//        nameLabel.textAlignment = NSTextAlignmentCenter;
//        nameLabel.backgroundColor = [UIColor redColor];
//        [self addSubview:nameLabel];
//        self.nameLabel = nameLabel;
//    }
//    return self;
//}

/**
 * 这个方法专门用来布局子控件,一般在这里设置子控件的frame
 * 当控件本身的尺寸发生改变的时候,系统会自动调用这个方法
 * 
 */
- (void)layoutSubviews{
    // 一定要调用super的layoutSubviews
    [super layoutSubviews];
    
    CGFloat shopW = self.frame.size.width;
    CGFloat shopH = self.frame.size.height;
    self.iconView.frame = CGRectMake(0, 0, shopW, shopW);
    self.nameLabel.frame = CGRectMake(0, shopW, shopW, shopH - shopW);
}

- (void)setShop:(XMGShop *)shop
{
    _shop = shop;
    
    self.nameLabel.text = shop.name;
    self.iconView.image = [UIImage imageNamed:shop.icon];
}

你可能感兴趣的:(控件的封装)