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

ios学习:UIButton,初识委托

2012-11-21 23:15 465 查看
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//第一种方法创建
UIButton *newBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

newBtn.frame = CGRectMake(50.0f, 50.0f, 100.0f, 50.0f);
[self.view addSubview:newBtn];

[newBtn setTitle:@"正常状态" forState:UIControlStateNormal];
[newBtn setTitle:@"选中状态" forState:UIControlStateHighlighted];
/*setTitle方法:设置button在某个状态下的的title
第二个参数 forState 在定义button的文字或者图片在何种状态下才会显示,是一个枚举类型
enum {
UIControlStateNormal               = 0,        常规状态显示
UIControlStateHighlighted          = 1 << 0,   高亮状态显示.点击时是高亮状态
UIControlStateDisabled             = 1 << 1,   禁用状态才会显示
UIControlStateSelected             = 1 << 2,   选中状态.什么时候才是选中状态?
UIControlStateApplication          = 0x00FF0000,  当应用程序标志时
UIControlStateReserved             = 0xFF000000 内部预留
};*/

[newBtn addTarget:self action:@selector(click:event:) forControlEvents:UIControlEventTouchUpInside];
/*给button添加事件,最后一个参数指明了事件类型,第二个参数指明了哪个方法对button的事件进行响应,该方法带两个参数,第一个是事件发生者,第二个是发生的事件,好像最多只能有两个.
第一个参数指明了谁提供响应方法,当第一个参数为nil时,将会从当前对象开始递归询问响应链直至找到方法提供者或者到跟响应链?
*/

[self.view addSubview:newBtn];

//第二种方法创建.这种方法在创建是没有指定button的type(风格),默认是UIButtonTypeCustom,重点在于这个属性只能在初始化时指定,初始化后是没法更改的
//所以一般不用这种创建方法
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100.0f, 100.0f, 200.0f, 50.0f)];

btn.tag = 100;
[btn setTitle:@"默认显示风格" forState:UIControlStateNormal];

[self.view addSubview:btn];
[btn release];
}

/*
提供给UIButton的事件响应方法
*/
-(void) click:(id)sender event:(UITouch *) touchEvent
{
/*
指定委托对象为当前类,则表明当前类实现了UIAlertViewDelegate协议时,应该实现了协议里的一些方法,则这些方法可以对alertview的一些事件进行响应
问题在于,当前类也可以不继承UIAlertViewDelegate协议啊,只是不进行对alertview的事件响应而已
*/
UIAlertView *alerView = [[UIAlertView alloc]
initWithTitle:@"Attention"
message:@"test"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:@"Cancel",
nil];

[alerView show];
[alerView release];

}

/*
当前类继承了UIAlertViewDelegate协议,实现协议里的其中一个方法,可以提供来响应alertview的事件响应
*/
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIAlertView *alerView = [[UIAlertView alloc]
initWithTitle:@"Attention123"
message:[NSString stringWithFormat:@"index at %d",buttonIndex]
delegate:nil
cancelButtonTitle:@"OK123"
otherButtonTitles:nil,
nil];

[alerView show];
[alerView release];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: