如何为UIButton添加动作



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

Use This

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

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

action:@selector(buttonClick:)

像这样使用

    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{
}

iOS 14.0+

你可以用UIAction代替addTarget:

            // Example: action to remove or add in the favorite list of recipes
    button.addAction(
        UIAction { _ in
            if self.isFavorite {
                self.isFavorite = false
                print("✅: Recipe is not favorite")
            } else {
                self.isFavorite = true
                print("✅ Recipe is favorite")
            }
        }, for: .touchUpInside)
action:@selector(buttonClick:)

Swift代码:

button.addTarget(self, action:"action_button", forControlEvents:.TouchUpInside)
...
func action_button() {
    //  implement me
}
  1. @objc
  2. 创建函数
  3. 将功能作为目标添加到UIButton。像这样:
menuButton.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)

最新更新