如何为UIButton添加操作

时间:2011-12-01 12:40:18

标签: 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 addTarget:self action:(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
btn.center = self.center;
[self addSubview:btn];

5 个答案:

答案 0 :(得分:9)

使用此

    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];

答案 1 :(得分:7)

使用 @selector()指定选择器。因此, action 参数看起来像

action:@selector(buttonClick:)

答案 2 :(得分:1)

action:@selector(buttonClick:)

答案 3 :(得分:1)

Swift代码:

button.addTarget(self, action:"action_button", forControlEvents:.TouchUpInside)
...
func action_button() {
    //  implement me
}

答案 4 :(得分:1)

像这样使用

    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{

}