因为为常见控件,需要经常调用创建的缘故,故可以将之写为分类。
并写一个类方法方便其调用,代码如下:(UIButton)
//
// UIButton+MY.h
// Copyright © 2016年 oh. All rights reserved.
#import <UIKit/UIKit.h>
@interface UIButton (MY)
+(UIButton *)buttonSetAttrs; //类方法,用以设置按键属性.
@end
//
// UIButton+MY.m
// Copyright © 2016年 oh. All rights reserved.
#import "UIButton+MY.h"
@implementation UIButton (MY)
+(UIButton *)buttonSetAttrs
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];//按键类型设置
[button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];//按键文字颜色设置(普通状态)
[button setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];//按键文字颜色设置(不可用状态)
button.titleLabel.font = [UIFont systemFontOfSize:14];//按键文字的字体大小设置
button.layer.borderWidth = 1.0f; //按键边框宽度设置
button.layer.borderColor = [UIColor lightGrayColor].CGColor;//按键边框颜色设置
button.layer.cornerRadius = 2;//设置按键边框圆角处的半径
return button;
}
@end
以上,即能够将所需按键创建出来并赋予它一些基本的属性。
(UITextField):
// UITextField+MY.h
// Copyright © 2016年 oh. All rights reserved.
#import <UIKit/UIKit.h>
@interface UITextField (MY)
+(UITextField *)textFieldSetAttrs; //类方法,用以设置textField属性
@end
// UITextField+MY.m
// Copyright © 2016年 oh. All rights reserved.
#import "UITextField+MY.h"
@implementation UITextField (MY)
+(UITextField *)textFieldSetAttrs
{
UITextField *textField = [[UITextField alloc]init];
textField.font = [UIFont systemFontOfSize:14]; //设置textField的字体大小
textField.textColor = [UIColor blackColor]; //设置textField的文字颜色
textField.textAlignment = NSTextAlignmentCenter; //设置textField为居中显示
textField.layer.borderWidth = 1.0f; //设置textField的边框宽度
textField.layer.cornerRadius = 5; //设置textField边框的圆角半径
textField.layer.borderColor =[UIColor lightGrayColor].CGColor;//设置textField的边框颜色
return textField;
}
@end
*注意,相比UITextField、UIButton是有不同的状态的,即普通、高亮、不可用等。因此设置UIButton的字体颜色、文字图片时切记应该与其所处的状态联系起来,没有状态限制则设置无效。