我有一个以编程方式创建的UIButton。我如何让这个UIButton将其补足事件发送给我的IBAction?
答案 0 :(得分:20)
addTarget:action:forControlEvents:
方法。
[myButton addTarget:myClass action:@selector(myEventHandler) forControlEvents: UIControlEventTouchUpInside];
答案 1 :(得分:15)
使用这行代码,您将通过编程方式触发UI按钮操作
[button sendActionsForControlEvents:UIControlEventTouchUpInside];
答案 2 :(得分:9)
[button addTarget:self
action:@selector(myMethod:)
forControlEvents:UIControlEventTouchUpInside];
喜欢魔术=)
答案 3 :(得分:2)
Swift 3.0
button.addTarget(self, action:#selector(funcName), for: UIControlEvents.touchUpInside)
答案 4 :(得分:1)
快捷键5
您还可以发送发件人以识别触摸的按钮。另外,不要忘记在函数名称之前添加objc:
private func setOnClicks() {
btn.addTarget(self, action: #selector(onBtnClick), for: .touchUpInside)
}
@objc func onBtnClick(_ sender: UIButton) -> Void {
print("touched \(sender.tag)")
}
答案 5 :(得分:0)
使用UIButton
轻松设置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
//标记:-单击操作手柄
/// Add vehicle button clicked action
@objc func addVehicleButtonClickedAction() {
}