How do you add an action to a button programmatically in xcode

后端 未结 10 1245
野的像风
野的像风 2020-11-29 21:40

I know how to add an IBAction to a button by dragging from the interface builder, but I want to add the action programmatically to save time and to avoid switching back and

10条回答
  •  鱼传尺愫
    2020-11-29 21:44

    Try this:

    Swift 4

    myButton.addTarget(self,
                       action: #selector(myAction),
                       for: .touchUpInside)
    

    Objective-C

    [myButton addTarget:self 
                 action:@selector(myAction) 
       forControlEvents:UIControlEventTouchUpInside];
    

    You can find a rich source of information in Apple's Documentation. Have a look at the UIButton's documentation, it will reveal that UIButton is a descendant of UIControl, which implements the method to add targets.

    --

    You'll need to pay attention to whether add colon or not after myAction in action:@selector(myAction)

    Here's the reference.

提交回复
热议问题