I add custom button to navigation controller
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@\"back.png\"]
Adding Button either in left or right with title or without title as per the requirement,
func addBarButton(image: UIImage?, isLeft: Bool = true, title: String? = nil, font: UIFont = UIFont.systemFont(ofSize: 16), tintColor: UIColor = R.color.textfieldColor() ?? .black) {
if let navController = self.navigationController {
let navBar = navController.navigationBar
navBar.isHidden = false
navBar.isTranslucent = false
let btn = UIButton.init(type: .custom)
if let img = image {
btn.setImage(img, for: UIControl.State.normal)
}
if let titleTxt = title {
btn.setTitle(titleTxt, for: .normal)
btn.setTitleColor(tintColor, for: .normal)
btn.titleLabel?.font = font
}
btn.frame = CGRect.init(x: 0, y: 0, width: 35, height: 35)
btn.adjustsImageWhenHighlighted = false
let barButton = UIBarButtonItem.init(customView: btn)
if isLeft {
btn.addTarget(self, action: #selector(self.btnLeftNavigationClicked), for: UIControl.Event.touchUpInside)
btn.tintColor = tintColor
if let tabBar = self.tabBarController {
tabBar.navigationItem.leftBarButtonItem = nil
tabBar.navigationItem.leftBarButtonItem = barButton
} else {
self.navigationItem.leftBarButtonItem = nil
self.navigationItem.leftBarButtonItem = barButton
}
} else {
btn.addTarget(self, action: #selector(self.btnRightNavigationClicked), for: UIControl.Event.touchUpInside)
btn.tintColor = tintColor
if let tabBar = self.tabBarController {
tabBar.navigationItem.rightBarButtonItem = barButton
} else {
self.navigationItem.rightBarButtonItem = barButton
}
}
}
}
Right button action
@objc func btnRightNavigationClicked(sender: UIButton) {
// add your logic here
}
Left button action
@objc func btnLeftNavigationClicked(sender: UIButton) {
guard let navigationController = self.navigationController else {
return
}
navigationController.popViewController(animated: true)
}