欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS开发--UIKit控件之UIButton(按钮)

程序员文章站 2022-07-03 11:42:52
(注:本文为本人日常开发中所遇到的,使用到的一些方法属性,作为备忘) UIButton与UIView一样,是做iOS开发中最常用、常见的一个UIKit控件。 UIButto...

(注:本文为本人日常开发中所遇到的,使用到的一些方法属性,作为备忘)

UIButton与UIView一样,是做iOS开发中最常用、常见的一个UIKit控件。

UIButton继承自UIControl,而UIControl继承自UIView,所以UIButton也可以说是UIView的一个子类。

在任何iOS应用中,UIButton都是随处可见的,它可以与用户进行交互,传递事件!

创建UIButton

 1 // 实例化(创建)按钮
 2     /**
 3      *  Type取值:
 4      *   1. UIButtonTypeContactAdd  : 加号按钮
 5      *   2. UIButtonTypeCustom      : 自定义按钮
 6      *   3. UIButtonTypeDetailDisclosure    : 'i'字按钮
 7      *   4. UIButtonTypeInfoDark    : 'i'字按钮
 8      *   5. UIButtonTypeInfoLight   : 'i'字按钮
 9      *   6. UIButtonTypeRoundedRect : 圆角按钮(现在设置这个最终效果并不是圆角)
10      *   7. UIButtonTypeSystem      : 效果与上面的RoundedRect一样
11      */
12     UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
13     // 设置背景颜色
14     button.backgroundColor = [UIColor lightGrayColor];
15     // 设置区域范围
16     button.frame = CGRectMake(110, 234, 100, 100);
17     // 添加到View上
18     [self.view addSubview:button];

属性

 

 1     // 设置是否选中状态
 2     button.selected = NO;
 3     // 设置是否接收触摸事件
 4     button.enabled = YES;
 5     // 设置tag值
 6     button.tag = 0;
 7     // 设置按钮标题文字的字体大小
 8     button.titleLabel.font = [UIFont systemFontOfSize:18.0f];
 9     // 通过设置这个属性,可以让按钮的文字适应按钮的区域显示
10     // NSLineBreakByCharWrapping    也可以设置成这个,效果一样
11     button.lineBreakMode = NSLineBreakByWordWrapping;
12     // 设置圆角直径
13     button.layer.cornerRadius = 10.0f;
14     // 剪切超出部分
15     button.layer.masksToBounds = YES;
16     // 边框宽度
17     button.layer.borderWidth = 1.0f;
18     // 边框颜色
19     button.layer.borderColor = [UIColor purpleColor].CGColor;

 

方法

 1     // 设置按钮状态标题文字
 2     /**
 3      * State取值:
 4      *  1. UIControlStateNormal     : 普通状态(默认状态)
 5      *  2. UIControlStateSelected   : 选中状态
 6      *  3. UIControlStateHighlighted : 高亮状态
 7      *  4. UIControlStateDisabled   : 禁用状态
 8      *  平常开发用的到的状态就这四个
 9      */
10     [button setTitle:@"按钮" forState:UIControlStateNormal];
11     // 设置按钮状态图标
12     // 这里state的取值与上面相同
13     [button setImage:[UIImage imageNamed:@"01.png"] forState:UIControlStateNormal];
14     // 设置按钮状态背景图
15     // 这里state的取值与上面相同
16     [button setBackgroundImage:[UIImage imageNamed:@"02.png"] forState:UIControlStateNormal];
17     // 添加(绑定)点击事件
18     /**
19      * 参数说明: 
20      *  target          : 事件监听对象,一般传self
21      *  action          : 回调的事件方法,只能传按钮本身一个参数
22      *  ControlEvents   : 监听类型
23      *      UIControlEventTouchUpInside : 单击
24      *      UIControlEventTouchCancel   : 触摸取消
25      *      UIControlEventTouchDown     : 触摸完成
26      *  到目前为止,我用的最多的就是单击事件,基本很少用到取消与完成
27      */
28     [button addTarget:self action:@selector(ButtonTouchEvent:) forControlEvents:UIControlEventTouchUpInside];

事件

- (void)ButtonTouchEvent:(UIButton *)sender {
    // 按钮点击事件回调处理
    
    // 设置按钮选中技巧
    sender.selected = !sender.selected;
}