如何使用 Button 制作自定义视图

How to make a custom view with Button

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

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

我该如何解决这个问题?

方法一: 您可以使用 nib 文件 (.XIB) 轻松创建可重复使用的视图,并将您自己的自定义 UI 视图 class 分配给它以引用标签和按钮。

然后在您的每个视图控制器中,您可以通过编程方式添加这些子视图,并使用这些引用来调用您的视图控制器独有的函数。

例子

    if let yourView = Bundle.main.loadNibNamed("yourView", owner:self, options:nil)?.first as? yourView //references your reusable custom view
yourView.yourLabel.text = "Your String Here" //change the label according to which view controller
yourView.yourButton.addTarget(self, action: #selector(ViewController.yourFunction(sender:)), for: .touchUpInside) //add function according to view controller
self.view.addSubview(yourView)

方法二: 或者,根据您的 preference/functionality,您可能更愿意使用单个视图和视图控制器。为此,只需根据使用 prepareForSegue 或 protocols/delegate.

传递给它的数据更改您的标签或函数

创建一个带有标签和按钮的 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
        }
    }
}