从视图中不显示的子类创建按钮

时间:2019-01-29 02:06:56

标签: swift uibutton subclass

解释为什么以下代码没有在我的视图中放置按钮?

按钮类

class CustomButton: UIButton {

    var button = UIButton()

    func makeButton() {
        button.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
        button.center = self.center
        button.setTitle("PRESS", for: .normal)
        button.backgroundColor = UIColor.red
        button.addTarget(self, action: #selector(ViewController.buttonPressed), for: .touchUpInside)
        self.addSubview(button)
    }
}

主类

class ViewController: UIViewController {

    var button: CustomButton?

    override func viewDidLoad() {
        super.viewDidLoad()

        button?.makeButton()
    }

    @objc func buttonPressed() {
        print("woohoo!")
    }
}

1 个答案:

答案 0 :(得分:1)

您需要完全重做CustomButton类。它不应具有button属性。它应该初始化自己。

目标的设置属于视图控制器,而不是按钮类。

更新的按钮代码:

class CustomButton: UIButton {
    init() {
        super.init(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        setTitle("PRESS", for: .normal)
        backgroundColor = UIColor.red
    }

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

更新的视图控制器:

class ViewController: UIViewController {
    var button = CustomButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(button)
        button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
    }

    @objc func buttonPressed() {
        print("woohoo!")
    }
}