简体   繁体   中英

How to add action for UIButton

I am new to iPhone technology. Please anyone tell me how to add action for 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];

You specify selectors using @selector() . So, the action parameter looks like,

action:@selector(buttonClick:)

Swift code:

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

Use Like This

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

and add your selector method

-(IBAction)btnTapped:(id)sender{

}
action:@selector(buttonClick:)
  1. Create a function with @objc
  2. add the function as a target to the UIButton . like so:
menuButton.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)

Since Ios14, you can use UIAction instead of 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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