Saturday, 18 January 2020

How do I pass data from one VC to another using closures in swift instead of delegates?

I have two VCs currently, one that displays a counter UILabel and another that displays a button, pressing which is supposed to increment the UILabel on the original VC by one.

I'm still learning Swift, and I know how to solve this issue using delegates, but want to learn how to do so using closures, which I'm finding a little difficult to do without seeing an example; hence the bountied question.

Here is my first VC with the UILabel counter:

var tappedCount: Int = 10

lazy var label: UILabel = {
    let label = UILabel()
    label.text = "\(tappedCount)"
    label.textAlignment = .center
    label.font = UIFont(name: "Copperplate", size: 90)
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    navigationItem.title = "Navigation Controller"
    navigationController?.navigationBar.isTranslucent = false
    view.addSubview(label)
    view.addSubview(button)

    let nextButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(moveToSecond))
    navigationItem.rightBarButtonItem = nextButton

    label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
  }

@objc func moveToSecond() {
    show(SecondViewController(), sender: self)
}

and here is my second VC with the button:

class SecondViewController: UIViewController {

    var callback : (() -> Void)?

    @objc func buttonPressed() {
        print("hello")
    }

    let button: UIButton = {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
        button.setTitle("HELLO", for: .normal)
        button.backgroundColor = .red
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        view.addSubview(button)

        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.heightAnchor.constraint(equalToConstant: 100).isActive = true
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true

           }
    }


from How do I pass data from one VC to another using closures in swift instead of delegates?

No comments:

Post a Comment