Iphone 如何为UIButton添加操作
我不熟悉iPhone技术。请告诉我如何为UIButton添加操作Iphone 如何为UIButton添加操作,iphone,objective-c,ios,ios4,Iphone,Objective C,Ios,Ios4,我不熟悉iPhone技术。请告诉我如何为UIButton添加操作 UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(0, 0, 100, 25); btn.backgroundColor = [UIColor clearColor]; [btn setTitle:@"Play" forState:UIControlStateNormal]; [btn addTarge
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 25);
btn.backgroundColor = [UIColor clearColor];
[btn setTitle:@"Play" forState:UIControlStateNormal];
[btn addTarget:self action:(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
btn.center = self.center;
[self addSubview:btn];
您可以使用@selector()指定选择器。动作参数看起来像
action:@selector(buttonClick:)
用这个
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Swift代码:
button.addTarget(self, action:"action_button", forControlEvents:.TouchUpInside)
...
func action_button() {
// implement me
}
像这样使用
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(0, 0, 100, 25);
btn.backgroundColor = [UIColor clearColor];
[btn setTitle:@"Play" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
btn.center = self.center;
[self addSubview:btn];
并添加选择器方法
-(IBAction)btnTapped:(id)sender{
}
不是关于这个问题,但你这里有内存泄漏。如果以后不调用释放按钮,则不要调用保留按钮。不需要retain,因为该按钮不是ivar并且是自动释放的。已删除内存泄漏。
-(IBAction)btnTapped:(id)sender{
}