出發(fā)點(diǎn)
每次添加控件都需要
addSubview:
其次控件的屬性設(shè)置恼五、方法經(jīng)常跨函數(shù),無(wú)法快速查找
對(duì)比
常規(guī)設(shè)置
self.titleLabel = [[UILabel alloc]init];
self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.titleLabel.textColor = [UIColor darkTextColor];
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.titleLabel.font = [UIFont systemFontOfSize:20];
[self.navView addSubview:self.titleLabel];
self.titleLabel.hh_centerX = 0;
self.titleLabel.hh_centerY = 0;
self.titleLabel.hh_centerYCS.constant = 11;
優(yōu)化后
[self.view hh_addLabel:^(UILabel *label) {
self.label = label;
label.textColor = [UIColor redColor];
label.font = [UIFont systemFontOfSize:15];
label.textAlignment = NSTextAlignmentCenter;
} constraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view).offset(100);
make.centerX.equalTo(self.view);
}];
button:方法
[self.view hh_addButton:^(UIButton *button) {
self.button = button;
[button setImage:[UIImage imageNamed:@"action_picture"] forState:UIControlStateNormal];
} action:^(UIButton *sender) {//button點(diǎn)擊事件
NSLog(@"點(diǎn)擊了按鈕");
} constraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.label).offset(50);
make.centerX.equalTo(self.view);
}];
textField:方法
[self.view hh_addTextField:^(UITextField *textField) {
self.textField = textField;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.placeholder = @"請(qǐng)輸入文字,不超過十個(gè)字";
[textField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
textField.maxCharacters = 10;//設(shè)置最大字?jǐn)?shù)
} action:^(UITextField *textField, BOOL isOverMax) {//字?jǐn)?shù)改變回調(diào)
NSLog(@"isOverMax==YES,超過了字?jǐn)?shù)限制");
} constraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.button.mas_bottom).offset(50);
make.centerX.equalTo(self.view);
}];
說明
1、為何第一個(gè)屬性設(shè)置block不需要弱引用歧寺,此和
masonry
等同,并沒有對(duì)象引用block棘脐,屬性設(shè)置之后就會(huì)被釋放斜筐。
2、action
事件以對(duì)象的內(nèi)存地址為key
存儲(chǔ)在actionDict
中蛀缝,action
block中需要使用弱引用顷链。當(dāng)然也可以不用,只需要打破環(huán)路即可屈梁,把視圖的actionDict
置為nil
即可嗤练,詳見Demo。在基類調(diào)用如下函數(shù):
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
if (!self.navigationController.topViewController)///過濾非銷毀的視圖在讶,如push進(jìn)來的上層界面
[self enumSubViewsTree:self.view];
}
- (void)enumSubViewsTree:(UIView *)view
{//遞歸遍歷子控件煞抬,把存有block的actionDict置為nil
if (view.actionDict) view.actionDict = nil;
for (UIView *subV in view.subviews)[self enumSubViewsTree:subV];
}
3、此分類包含了常用的控件构哺,需要依賴第三方框架masonry
4革答、之所以為務(wù)虛篇
,是因?yàn)榇朔诸惒]有改變實(shí)際的代碼量曙强,只是以高內(nèi)聚的形式展示残拐,聚合了屬性,事件以及約束碟嘴。
下載地址:Demo地址