Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom anonymous closure navigation back button inside of UiView()

I have a question, how is it possible to implement the creation of a custom back navigation button inside an UIView(). I have a main controller which contains a collectionView, clicking on any cell goes to a second controller which contains a tableView. I created a separate custom view inside the tableView headers where I added labels, pictures, buttons. I need when clicking a backButton inside a custom view, it will go to the main controller. How can be implemented? I making app only programmatically – (No Storyboard)

CustomView.swift

lazy var backButton: UIButton = {
    let button = UIButton(type: .system)
    let image = UIImage(systemName: "chevron.left")
    button.setImage(image, for: UIControl.State())
    button.tintColor = .white
    button.isHidden = true
    button.addTarget(self, action: #selector(goToBack), for: .touchUpInside)
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

@objc func goToBack() {
    
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First add a callback function in the CustomView. Then call this callback closure from goToBack() method.

class CustomView: UIView {
    
    var backButtonTapped: (() -> Void)?
    
    lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        let image = UIImage(systemName: "chevron.left")
        button.setImage(image, for: UIControl.State())
        button.tintColor = .white
        button.isHidden = true
        button.addTarget(self, action: #selector(goToBack), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    @objc func goToBack() {
        backButtonTapped?()
    }
}

In UIViewController where you initialise this CustomView, give the action of the closure.

let view = CustomView()
view.backButtonTapped = { [weak self] in
    self?.navigationController?.popViewController(animated: true)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading