如何以编程方式创建按钮操作
How To Programatically Create A Button Action
我是 Xcode 的新开发人员,我一直在努力掌握它。对于我的应用程序,我正在创建一个水平滚动视图,其中包含按钮。在 viewDidLoad() 中,我创建了我的 scrollView 和其中的 3 个不同的按钮,但我不太确定如何给按钮一个动作。我想要它,这样如果你点击某个按钮,它就会带你到那个特定的视图控制器 Here's the code I wrote
您可以使用 addTarget(_:action:for:)
https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let aButton = UIButton(type: .system)
aButton.setTitle("Tap me", for: .normal)
aButton.addTarget(self, action: #selector(onTapButton), for: .touchUpInside)
}
@objc func onTapButton() {
}
}
创建函数来处理触摸。由于您是在代码中进行操作,因此无需添加 @IBAction。
@objc
func buttonTapped(_ sender: Any?) {
guard let button = sender as? UIButton else {
return
}
print(button.tag)
}
将目标添加到按钮
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
您可以为所有按钮使用相同的目标。为每个按钮添加不同的标签,以便您知道触摸了哪个按钮。
https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget
我是 Xcode 的新开发人员,我一直在努力掌握它。对于我的应用程序,我正在创建一个水平滚动视图,其中包含按钮。在 viewDidLoad() 中,我创建了我的 scrollView 和其中的 3 个不同的按钮,但我不太确定如何给按钮一个动作。我想要它,这样如果你点击某个按钮,它就会带你到那个特定的视图控制器 Here's the code I wrote
您可以使用 addTarget(_:action:for:)
https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let aButton = UIButton(type: .system)
aButton.setTitle("Tap me", for: .normal)
aButton.addTarget(self, action: #selector(onTapButton), for: .touchUpInside)
}
@objc func onTapButton() {
}
}
创建函数来处理触摸。由于您是在代码中进行操作,因此无需添加 @IBAction。
@objc
func buttonTapped(_ sender: Any?) {
guard let button = sender as? UIButton else {
return
}
print(button.tag)
}
将目标添加到按钮
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
您可以为所有按钮使用相同的目标。为每个按钮添加不同的标签,以便您知道触摸了哪个按钮。
https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget