首页 > 解决方案 > 如何使用 Button 制作自定义视图

问题描述

我想制作一个带有标签和按钮的自定义视图。

我将不得不在多个视图控制器中显示这个视图,但是点击按钮的动作是不同的,所有视图控制器都是如此。

我怎么解决这个问题。?

标签: iosuiviewswift4

解决方案


创建一个带有标签和按钮的 UIView 子类。在该视图中添加一个可选的闭包属性。

class CustomView: UIView {

    var buttonAction: (()->Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    func commonInit() {
        //add label and button
        let button = UIButton()
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    }
    @objc func buttonTapped(_ sender: UIButton) {
        if let buttonAction = self.buttonAction {
            buttonAction()
        }
    }
}

并在任何视图控制器中添加此视图的实例。要在该特定视图控制器中获取按钮操作,请将闭包分配给可选的闭包属性。

class ViewController: UIViewController {
    let customView = CustomView()
    override func viewDidLoad() {
        super.viewDidLoad()
        // add customView in self.view or any other view
        customView.buttonAction = { [weak self] in
            print("button tapped")
            //do your actions here
        }
    }
}

推荐阅读