繁体   English   中英

如何为 UIButton 添加操作

[英]How to add action for 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];

用这个

    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参数看起来像,

action:@selector(buttonClick:)

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{

}
action:@selector(buttonClick:)
  1. 使用@objc 创建一个@objc
  2. 将 function 作为目标添加到UIButton 像这样:
menuButton.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)

从 Ios14 开始,您可以使用 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM