首页 > 解决方案 > 在 Swift 4 中以编程方式创建 UIButton 但出现错误

问题描述

我正在尝试在 Swift 4 中创建一个 UIButton,但是当我尝试调用 addTarget 函数时,我在“MyView”类中不断收到“预期声明”错误。我已经在其他类中完成了相同的代码,并且从未收到错误。我错过了什么吗?谢谢。

import Foundation
import UIKit

protocol MyDelegate: class {
    func onButtonTapped()
}

class OtherViewController: UIViewController {

}

class MyViewController: UIViewController, MyDelegate {
    func onButtonTapped() {

        let nextViewController = OtherViewController()
        navigationController?.pushViewController(nextViewController, animated: false)

}

    var myView: MyView!
    override func viewDidLoad() {
        super.viewDidLoad()
        myView.delegate = self
    }
}

class MyView: UIView {
    weak var delegate: MyDelegate?

    let button = UIButton()
    button.addTarget(self, action: #selector(buttonTapped),for: .touchUpInside)

    func buttonTapped() {
        self.delegate?.onButtonTapped()
    }
}

标签: swiftxcodeuser-interfaceuibutton

解决方案


您不能 addTarget 或调用类空间中的任何方法,此空间用于声明错误提示。

要解决这个问题,你可以这样做

let button:UIButton =
{
    let btn = UIButton()
    btn.addTarget(self, action: #selector(buttonTapped),for: .touchUpInside)
    return btn
}()

或者

   let button:UIButton = UIButton()

override init(frame: CGRect) {
    super.init(frame: frame)
    button.addTarget(self, action: #selector(buttonTapped),for: .touchUpInside)

}
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

在这两种情况下,您都必须将 @objc 注释添加到 buttonTapped 函数,因为选择器必须引用 @objc 函数。

所以会是这样

   @objc func buttonTapped(){}

您还需要将此按钮添加到视图中,以便将其绘制到屏幕上。

view.addSubView(button)

推荐阅读