黑马程序员技术交流社区

标题: 纯代码添加监听方法 [打印本页]

作者: 余丽丽    时间: 2015-8-6 21:59
标题: 纯代码添加监听方法
在OC开发中,Storyboard中的所有操作都可以通过代码实现,程序员一定要熟练掌握代码布局界面的能力!

设置控件监听方法的示例代码如下:

[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

提示:

1> addTarget方法定义在UIControl类中,这意味着可以给所有继承自UIControl类的对象添加监听方法

2> 监听方法的第一个参数就是对象本身

3> 监听方法的第二个参数是监听控件的事件

例如:
//1.使用类创建一个按钮对象
   // UIButton *headbtn=[[UIButton alloc] initWithFrame:CGRectMake(100 ,100, 100, 100)];
     //设置按钮对象为自定义型
    UIButton *headbtn=[UIButton buttonWithType:UIButtonTypeCustom];
   
   //2.设置对象的各项属性
    //(1)位置等通用属性设置
     headbtn.frame=CGRectMake(100, 100, 100, 100);
     
     //(2)设置普通状态下按钮的属性
     [headbtn setBackgroundImage:[UIImage imageNamed:@"i"] forState:UIControlStateNormal];
     [headbtn setTitle:@"点我!" forState:UIControlStateNormal];
     [headbtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
     
    //(3)设置高亮状态下按钮的属性
     [headbtn setBackgroundImage:[UIImage imageNamed:@"a"] forState:UIControlStateHighlighted];
     [headbtn setTitle:@"还行吧~" forState:UIControlStateHighlighted];
     [headbtn setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
     
     //3.把对象添加到视图中展现出来
     [self.view addSubview:headbtn];
     //注意点!
     self.headImageView=headbtn;




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2