標籤:
用途 : 一個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);}
自訂View步驟學習筆記