【问题标题】:How To Programatically Create A Button Action如何以编程方式创建按钮操作
【发布时间】:2020-08-18 10:07:56
【问题描述】:

我是 Xcode 的新开发人员,我一直在努力掌握它。对于我的应用程序,我正在创建一个带有按钮的水平滚动视图。在 viewDidLoad() 中,我在其中创建了我的 scrollView 和 3 个不同的按钮,但我不太确定如何为按钮提供操作。我想要它,这样如果你点击某个按钮,它会将你带到那个特定的视图控制器Here's the code I wrote

【问题讨论】:

  • 将代码作为文本而不是图像添加到您的问题中。
  • 我在这里看到了几个问题。首先,您没有对任何视图设置任何约束,因此您的 UI 将无法正确显示。其次,您需要向按钮添加目标,以便它们可以响应事件 (button.addTarget(self, action: action: #selector(someObjcMethod), for: .touchUpInside))

标签: ios swift iphone xcode uikit


【解决方案1】:

您可以使用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() {
  
  }
}

【讨论】:

    【解决方案2】:

    创建函数来处理触摸。由于您在代码中进行操作,因此无需添加 @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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多