码迷,mamicode.com
首页 > 其他好文 > 详细

UIButton 学习知识点

时间:2015-08-29 23:08:51      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

UIButton(按钮):是iOS中提供的用来响应用户交互的控件,可以显示文字,也可以显示图片

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

使用时应注意两点:

  1. 创建对象使用便利构造器方法,所以无需release
  2. 记得要制定按钮的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;//关灯 -- 显示正常状态图片

    }

     */

}

UIButton 学习知识点

标签:

原文地址:http://www.cnblogs.com/iamfoolish/p/4769859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!