一、自定义按钮
1、点击按钮时消除变暗状态
UIButton *customBtn = [UIButton buttonWithType:UIButtonTypeCustom];
如果只设置了普通状态下的按钮图片那么点击时(高亮状态下)图片会变暗
[customBtn setBackgroundImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
如下设置即可消除变暗效果
customBtn.adjustsImageWhenHighlighted = NO;
2、属性比较
@property(nonatomic,getter=isSelected) BOOL selected;
@property(nonatomic,getter=isEnabled) BOOL enabled; // default is YES. if NO, ignores touch events and subclasses may draw differently
如果设置选择状态为NO,按钮可以接收点击事件,但是如果设置按钮的enable属性为NO,按钮不能接收点击事件
enable属性的效果如下:
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor = [UIColor orangeColor];
[btn setBackgroundImage:[UIImage imageNamed:@"2"] forState:UIControlStateNormal];
btn.selected = NO;
btn.frame = CGRectMake(100, 100, 40, 40);
[self.view addSubview:btn];
}
- (void)btnClick:(UIButton *)btn {
btn.enabled = !btn.enabled;
}
点击后:
3、showsTouchWhenHighlighted
设置了这个属性,点击按钮会发光。
4、contentVerticalAlignment
看一下效果就知道咯
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 100, 100);
[btn setTitle:@"aaaaaaaaaaaaaa" forState:UIControlStateNormal];
btn.titleLabel.numberOfLines = 0;
btn.backgroundColor = [UIColor orangeColor];
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
[self.view addSubview:btn];
5、setExclusiveTouch
很多时候,一个界面会有多个按钮,如果这些按钮同时点击,会发生混乱,对每个按钮设置这个属性,就可以避免。(更为简便的方法是设置一个视图的这个属性)
6、圆角设置
#define BTN_SIZE 50
@implementation CustomBtn
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
return CGRectMake((self.frame.size.width - BTN_SIZE) / 2, 0, BTN_SIZE, BTN_SIZE);
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
return CGRectMake(0, BTN_SIZE - 3, self.frame.size.width, self.frame.size.height - BTN_SIZE + 3);
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_plainBtn = [CustomBtn buttonWithType:UIButtonTypeCustom];
_plainBtn.titleLabel.layer.cornerRadius = 5;
_plainBtn.titleLabel.clipsToBounds = YES;
_plainBtn.imageView.layer.cornerRadius = BTN_SIZE / 2;
_plainBtn.imageView.clipsToBounds = YES;
[_plainBtn setImage:[UIImage imageNamed:@"6"] forState:UIControlStateNormal];
[_plainBtn setTitle:@"111" forState:UIControlStateNormal];
_plainBtn.titleLabel.backgroundColor = [UIColor orangeColor];
_plainBtn.frame = CGRectMake(100, 100, 70, 70);
[self.view addSubview:_plainBtn];
}