学了几天了,今天复习整理一下,虽然掌握的不全面,但还是要总结一下,好慢慢积累补充UIButton是UIControl的一种创建方法有两种
一种是动态的创建
UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80 , 50)];
//设置button1标题和背景图片
[button1 setTitle:@"button1" forState:UIControlStateNormal];
[button1 setBackgroundImage:[UIImage imageNamed:@"pic"] forState:UIControlStateHighlighted];
//按下按钮的特效
button1.adjustsImageWhenHighlighted = NO;
button1.adjustsImageWhenDisabled = NO;
button1.showsTouchWhenHighlighted = YES;
另一种是静态的创建
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//初始化设置
//设置button2的位置和大小
button2.frame = CGRectMake(110, 0, 50, 50);
[button2 setImage:[UIImage imageNamed:@"pic"] forState:UIControlStateNormal];
//forState属性决定一些显示特性在何种条件下显示
添加触摸事件
[button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button2 addTarget:self action:@selector(buttonPressed2:) forControlEvents:UIControlEventTouchUpInside];
完整代码
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80 , 50)];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button2.frame = CGRectMake(110, 0, 50, 50);
[button1 setTitle:@"button1" forState:UIControlStateNormal];
[button2 setImage:[UIImage imageNamed:@"pic"] forState:UIControlStateNormal];
[button1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button1 setBackgroundImage:[UIImage imageNamed:@"pic"] forState:UIControlStateHighlighted];
button1.adjustsImageWhenHighlighted = NO;
button1.adjustsImageWhenDisabled = NO;
button1.showsTouchWhenHighlighted = YES;
[self.view addSubview:button1];
[self.view addSubview:button2];
[button1 release];
[button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button2 addTarget:self action:@selector(buttonPressed2:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)buttonPressed:(id)sender
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"my view" message:@"点击BUTTON1" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert1 addButtonWithTitle:@"取消"];
[alert1 show];
}
- (IBAction)buttonPressed2:(id)sender
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"my view" message:@"点击BUTTON2" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert1 addButtonWithTitle:@"取消"];
[alert1 show];
}
暂时学习这么多,有新的发现了再继续补充
[button1 release]是因为创建的时候alloc,button1对象的retainCount为1 addSubview一次 会把传过去的对象retain一次,那么retainCount为2,释放一次 button1的所有者只剩下self.view retainCount为1