I want to make a custom view which will be having a label and a button.
I will have to show this view in multiple view controllers, but the action on tapping the button is different is all view controllers.
How can i Solve this problem.?
Create a UIView subclass with a label and a button. Add an optional closure property in that view.
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()
}
}
}
And add an instance of this view in any view controller. To get the button action in that particular view controller assign a closure to the optional closure property.
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
}
}
}
Method 1: You can easily create a reusable view using nib files (.XIB) and assign your own custom UI view class to it to reference the label and button.
Then in each of your view controllers you can add these subviews programmatically and use those references to call the function unique to your view controller.
Example
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)
Method 2: Alternatively, you may prefer to use a single view and view controller instead depending on your preference/functionality. To do this simply change your label or function depending on what data was passed to it from using prepareForSegue or protocols/delegate.