我想创建一个自定义视图,其中将包含一个标签和一个按钮。
我将不得不在多个视图控制器中显示该视图,但是所有视图控制器在点击按钮时的动作都不同。
我该如何解决这个问题。
答案 0 :(得分:1)
方法1: 您可以使用nib文件(.XIB)轻松创建可重用的视图,并为其分配自定义UI视图类以引用标签和按钮。
然后,您可以在每个视图控制器中以编程方式添加这些子视图,并使用这些引用来调用视图控制器特有的功能。
示例
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)
方法2: 另外,根据您的喜好/功能,您可能更喜欢使用单个视图和视图控制器。为此,只需根据使用prepareForSegue或protocols / delegate传递给它的数据来更改标签或函数。
答案 1 :(得分:1)
创建带有标签和按钮的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
}
}
}