自定义View步骤学习笔记

用途 : 一个View内部的子控件比较多的时候可以自定义一个View,把它内部的子控件屏蔽起来(就像苹果的导航栏上面的UIBarButton,你是通过BarButtonitem来修改显示的内容)

1.重写 initWithFrame 和 awakeFromNib(一般两个都要写),然后在写一个初始化的方法,在初始化方法中添加子控件和初始化子控件(当然也可以使用懒加载的方式来初始化子控件)

2.在layoutSubviews方法中调整子控件的位置和尺寸

3.提供一个模型属性,让外界来设置显示的内容

效果图: 

(当然这种效果也可以通过自定义Button来实现)

代码实现懒加载的方式(使用懒加载的好处是可以单独方法中设置子控件的属性,这样业务更加清晰)

文件有 : KFShopView和 KFShop

/*************** KFShop.h文件 ***************/

@interface KFShop : NSObject

@property (copy, nonatomic) NSString * name;

@property (copy, nonatomic) NSString * icon;

// 提供一个方法用于字典转模型

// 开发中我们要面对模型开发,而不是面对字典开发.例如 属性名如果写错了,编译器马上报错.如果是使用字典,写错了编译器并不会报错

- (instancetype)initWithDict:(NSDictionary *)dict;

+ (instancetype)shopWithDict:(NSDictionary *)dict;


@implementation KFShop

- (instancetype)initWithDict:(NSDictionary *)dict

{

    if(self = [super init])

    {

        self.name = dict[@"name"];

        self.icon = dict[@"icon"];

    }

    return self;

}

+ (instancetype)shopWithDict:(NSDictionary *)dict;

{

    return [[self alloc] initWithDict:dict];

}

@end



/*************** KFShopView文件 ***************/

#import <UIKit/UIKit.h>

@class KFShop;

@interface KFShopView : UIView 

@property (strong, nonatomic) KFShop *shop;

+ (instancetype)shopView;

@end

@interface KFShopView()


@property (weak, nonatomic) UIImageView * imageView;


@property (weak, nonatomic) UILabel * nameLabel;

@end

 @implementation KFShopView

// 提供一个类方法用来快速创建shopView
+ (instancetype)shopView{
    
    KFShopView *shopView = [[self alloc] init];
        
    return shopView;

}

// 用到时才会创建imageView
- (UIImageView *)imageView{
    
    if(_imageView == nil){
        
        UIImageView * imageVeiw = [[UIImageView alloc] init];
        _imageView = imageVeiw;
        [self addSubview:_imageView];
    }
    
    return _imageView;

}

// 用到时才会创建nameLabel
- (UILabel *)nameLabel
{
    if(_nameLabel == nil)
    {
        UILabel * label = [[UILabel alloc] init];
        _nameLabel = label;
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_nameLabel];
    }
    
    return _nameLabel;

}

// 根据传进来的模型设置显示的内容
- (void)setShop:(KFShop *)shop
{
    _shop = shop;
    
    self.imageView.image = [UIImage imageNamed:self.shop.icon];
    self.nameLabel.text = shop.name;
}

// 布局子控件
- (void)layoutSubviews
{
    // 一定要调用super的方法
    [super layoutSubviews];
    
    CGFloat W = self.frame.size.width;
    CGFloat H = self.frame.size.height;
    
    self.imageView.frame = CGRectMake(0, 0, W, W);
    self.nameLabel.frame = CGRectMake(0, W, W, H - W);
}
原文地址:https://www.cnblogs.com/TangKaiFu/p/4620049.html