ios 如何为UIButton添加动作

xhv8bpkk  于 2023-01-22  发布在  iOS
关注(0)|答案(7)|浏览(157)

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

a8jjtwal1#

使用此

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

0ejtzxu12#

使用 @selector() 指定选择器。因此,action 参数如下所示:

action:@selector(buttonClick:)
hgc7kmma

hgc7kmma3#

银行代码:

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

ohtdti5x4#

像这样使用

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{

}
fumotvh3

fumotvh35#

action:@selector(buttonClick:)
hmae6n7t

hmae6n7t6#

1.使用@objc创建函数
1.将函数作为目标添加到UIButton。如下所示:

menuButton.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)
qvsjd97n

qvsjd97n7#

从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)

相关问题