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

Snail—UI学习之得到某组件的方法

2016-04-18 18:39 543 查看
第一种方法:依据传入函数的參数对象的tag属性区分

比方 多个button运行同一个方法,可是不同的方法运行时。里面的逻辑又不一样 那就得加以区分 这时能够用tag来差别

//再新建一个Button
UIButton * button2 = [UIButton buttonWithType:UIButtonTypeSystem];
button2.frame = CGRectMake(20, 60, 280, 30);
button2.tag = 2;
button2.backgroundColor = [UIColor redColor];
[button2 setTitle:@"点我2" forState:UIControlStateNormal];
//此action中得click:是代表有參数的click方法
[button2 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];

//自己定义按钮  UIButtonTypeCustom
UIButton * button3 = [UIButton buttonWithType:UIButtonTypeCustom];
button3.frame = CGRectMake(20, 100, 31, 30);

[button3 setTitle:@"点我3" forState:UIControlStateNormal];
button3.tag = 3;
//设置button的初始状态  已经选择的状态
button3.selected = NO;
//设置自己定义按钮两种状态下得不同图片
//未选中状态显示的是第一个图片 选中状态后是后边的一个图片
[button3 setImage:[UIImage imageNamed:@"star_icon@2x.png"] forState:UIControlStateNormal];

[button3 setImage:[UIImage imageNamed:@"star2_Gray@2x.png"] forState:UIControlStateSelected];
[button3 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button3];

}

//假设有多个按钮要触发同一个操作,可是又想实现不同按钮方法将运行不同操作时,就要推断一下是哪个按钮按下了
- (void)click:(UIButton *)button{
if (button.tag == 2) {
NSLog(@"button2 点我了");
}else if (button.tag == 3){
NSLog(@"button3 点我了");
}
}


2、能够通过设置全局变量来实现

#import "WJJRootViewController.h"

@interface WJJRootViewController (){
<span style="color:#FF0000;">//为全局变量 在此类的不论什么地方都能够得到此对象
UIButton * _button3;</span>
}

@end

@implementation WJJRootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
3、由于在一个界面中。我们要得到的都是此界面中得控件,所以能够通过以下的方法得到
UIButton * btn = (UIButton *)[self.view viewWithTag:3];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: