I implemented header(UIView) for my view controller but i cannot add target for the button inside at the UIView. I believe this is very understandable for everyone but i can add more detail if you want
MY View Controller Code inside loadView()
let headerViewModel = HeaderViewModel(title: "Farmers", helpAction: {self.navigationController?.popViewController(animated: true) // when debugging this //line doesn't work when adding })
let headerView = HeaderView(viewModel: headerViewModel)
MY Header UIView Code
import UIKit
protocol HeaderViewModelProtocol {
var title: String { get }
var color: UIColor { get }
var imageName: String? { get }
var backAction: (()->Void)? { get set}
var helpAction: (()->Void)? { get set}
}
struct HeaderViewModel: HeaderViewModelProtocol {
let title: String
var color: UIColor = UIColor.white
var imageName: String?
var backAction: (() -> Void)?
var helpAction: (() -> Void)?
}
class HeaderView: UIView {
let viewModel: HeaderViewModelProtocol
private var layer0: CAGradientLayer!
var backButton: UIButton = {
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
button.addTarget(HeaderView.self, action: #selector(tapBack), for: .touchUpInside)
button.backgroundColor = UIColor.red
button.tag=5
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .clear
button.tintColor = .white
button.setImage(UIImage(named: "back"), for: .normal)
return button
}()
var helpButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .clear
button.setImage(UIImage(named: "plus"), for: .normal)
button.tintColor = .white
return button
}()
init(viewModel: HeaderViewModelProtocol) {
self.viewModel = viewModel
super.init(frame: .zero)
loadView()
}
func loadView() {
if viewModel.backAction != nil {
backButton.addTarget(self, action: #selector(tapBack), for: .touchUpInside)
addSubview(backButton)
backButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 30).isActive = true
backButton.topAnchor.constraint(equalTo: topAnchor, constant: 36).isActive = true
backButton.widthAnchor.constraint(equalToConstant: 22).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 36).isActive = true
}
if viewModel.helpAction != nil {
helpButton.addTarget(self, action: #selector(tapHelp), for: .touchUpInside)
addSubview(helpButton)
helpButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -30).isActive = true
helpButton.topAnchor.constraint(equalTo: topAnchor, constant: 36).isActive = true
helpButton.widthAnchor.constraint(equalToConstant: 22).isActive = true
helpButton.heightAnchor.constraint(equalToConstant: 36).isActive = true
}
}
@objc func tapBack() {
viewModel.backAction?()
}
@objc func tapHelp() {
viewModel.helpAction?()
}
}
Thanks in advance everyone! You can contact me !