iOS开发 ☞ UIButton详解

一、自定义按钮
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];
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值