开发者

UIButton created programmatically. How do I send touch up's to an IBAction?

I have a UIButton which is created programmatically. How do I get this UIButton to se开发者_如何学Cnd its touch up events to an IBAction I have?


addTarget:action:forControlEvents: method.

[myButton addTarget:myClass action:@selector(myEventHandler) forControlEvents: UIControlEventTouchUpInside];

From http://developer.apple.com/library/ios/#documentation/uikit/reference/UIControl_Class/Reference/Reference.html.


with this line of code you will fire UIbutton action by programmatically

[button sendActionsForControlEvents:UIControlEventTouchUpInside];

For swift

button.addTarget(self, action:#selector(functionNameHere), for: UIControl.Event.touchUpInside)


[button addTarget:self 
           action:@selector(myMethod:)
 forControlEvents:UIControlEventTouchUpInside];

Like magic =)


Swift 3.0

button.addTarget(self, action:#selector(funcName), for: UIControlEvents.touchUpInside)


Swift 5

You can also send the sender to identify the touched button. Plus, don't forget to add objc before your function name:

private func setOnClicks() {
    btn.addTarget(self, action: #selector(onBtnClick), for: .touchUpInside)
}

@objc func onBtnClick(_ sender: UIButton) -> Void {
    print("touched \(sender.tag)")
}


Easily set add action for UIButton using addTarget(,action:,for:)

let addVehicleButton = UIButton() // Create a button
addVehicleButton.setTitle("Add vehicle", forState: .normal) // set title
addVehicleButton.frame = CGRectMake(20, 50, 50, 40) // setting frame
addVehicleButton.addTarget(self, action: #selector(addVehicleButtonClickedAction), for: .touchUpInside) // Add target and control event with trigger function selector
self.view.addSubview(addVehicleButton) // adding to superview

// MARK: - Click action handles

/// Add vehicle button clicked action
    @objc func addVehicleButtonClickedAction() {

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜