UIView的封裝

- #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
-  * 當控件自己的尺寸發生改變的時候,系統會自動調用這個方法
-  * 這個方法專門用來佈局子控件,通常在這裏設置子控件的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);
- }
- /**
-  *  重寫set方法
-  *  @param shop <#shop description#>
-  */
- - (void)setShop:(XMGShop *)shop
- {
-     _shop = shop;
-     
-     self.nameLabel.text = shop.name;
-     self.iconView.image = [UIImage imageNamed:shop.icon];
- }
- @end
相關文章
相關標籤/搜索