Home > database >  Custom anonymous closure navigation back button inside of UiView()
Custom anonymous closure navigation back button inside of UiView()

Time:04-25

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() {
    
}

CodePudding user response:

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)
}

CodePudding user response:

You will need to create a delegate for this. In your CustomView make a property weak var delegate: ButtonDelegate

protocol ButtonDelegate: class {
    func onTap()
}

And your ViewController holding the CustomView has do implement that protocol and do navigationController.popViewController() in the implemented onTap() method.

Call delegate?.onTap() in your CustomView goToBack() method.

  • Related