出發(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)輸入文字,不超過(guò)十個(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,超過(guò)了字?jǐn)?shù)限制");
} constraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.button.mas_bottom).offset(50);
make.centerX.equalTo(self.view);
}];
說(shuō)明
1、為何第一個(gè)屬性設(shè)置block不需要弱引用,此和
masonry等同,并沒(méi)有對(duì)象引用block,屬性設(shè)置之后就會(huì)被釋放。
2、action事件以對(duì)象的內(nèi)存地址為key存儲(chǔ)在actionDict中,actionblock中需要使用弱引用。當(dāng)然也可以不用,只需要打破環(huán)路即可,把視圖的actionDict置為nil即可,詳見(jiàn)Demo。在基類調(diào)用如下函數(shù):
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
if (!self.navigationController.topViewController)///過(guò)濾非銷毀的視圖,如push進(jìn)來(lái)的上層界面
[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)榇朔诸惒](méi)有改變實(shí)際的代碼量,只是以高內(nèi)聚的形式展示,聚合了屬性,事件以及約束。
下載地址:Demo地址