您的位置:首页 > 产品设计 > UI/UE

UIButton 学习知识点

2015-08-29 21:39 447 查看
UIButton(按钮):是iOS中提供的用来响应用户交互的控件,可以显示文字,也可以显示图片

核心功能:响应用户点击事件

使用时应注意两点:

创建对象使用便利构造器方法,所以无需release

记得要制定按钮的frame.

//1.创建按钮对象

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeSystem];

//2.配置相关属性

aButton.backgroundColor = [UIColor yellowColor];

aButton.frame = CGRectMake(30, 100, 300, 40);

//2.1设置按钮文字 -- 正常状态显示文字

[aButton setTitle:@"登录" forState:UIControlStateNormal];//正常状态

[aButton setTitle:@”登录你妹啊!,快去学习!”forState:UIControlStateHighlighted];//高亮状态,点击之后

//2.2 设置按钮文字颜色

[aButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];//正常状态文字颜色

[aButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];//高亮状态文字颜色

//2.3 给按钮添加响应事件 -- 对点击做出响应

//01:指定事件的响应对象. self -- 是当前AppDelegate类的对象

//02:指定事件的响应方法. 由target调用

//03:指定事件的响应时机.

[aButton addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];

//3.添加到父视图

[self.window addSubview:aButton];

//handleAction:方法可以有参数,但是最多只能有一个参数,而参数为点击的按钮对象

//当前AppDelegate对象调用该方法,处理按钮点击事件

- (void)handleAction:(UIButton *)sender {

//更改window的颜色 -- 灰色

//self.window.backgroundColor = [UIColor grayColor];

//随机颜色

sender.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];

}

//创建新的按钮, 添加不同状态下的照片(正常状态和选中状态)

//如果要给按钮设置图片,按钮状态必须是自定义状态

UIButton *lightBtn = [UIButton buttonWithType:UIButtonTypeCustom];

lightBtn.frame = CGRectMake(30, 230, 56, 59);

//给按钮设置图片 -- Normal正常状态

[lightBtn setImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal]; //图片的素材直接拖拽到工程的文件夹里边,在使用的时候将图片拖拽到双引号里边,此时显示的是图片的名字

//给按钮设置图片 -- 选中状态

[lightBtn setImage:[UIImage imageNamed:@"2"] forState:UIControlStateSelected];

//切换选中状态,不需要对按钮进行操作,修改选中属性即可

lightBtn.selected = NO;

//添加响应事件

[lightBtn addTarget:self action:@selector(handleOpen:) forControlEvents:UIControlEventTouchUpInside];

[self.window addSubview:lightBtn];

//按钮响应事件 -- 处理开关灯

- (void)handleOpen:(UIButton *)sender {

- //方法一:

sender.selected = !sender.selected;

//方法二:

/*

if (sender.selected == NO) {//之前是关灯

sender.selected = YES;//开灯 -- 显示选中状态图片

} else {//之前是开灯 -- 选中状态

sender.selected = NO;//关灯 -- 显示正常状态图片

}

*/

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: