Change leftBarButtonItem after longpress

35 Views Asked by At

I need change leftBarButtonItem after i do a long press, i have setup leftBarButtonItem in TabBarController and have long press action in UsersController, how I can do this?

TabBarController:

class TabViewController: TabmanViewController {

private var viewControllers = [ DashboardController(),ClientsController(), UsersController() ]
var viewModel = TabBarViewModel()
var coordinator: TabBarCoordinator?

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Dashboard"
    
    let rightItem = UIImage(named: "userIcon")
    let leftItem = UIImage(named: "backMenuButton")
    
    let rightButton = UIBarButtonItem(image: rightItem, style: .done, target: self, action: #selector(rightAction))
    let leftButton = UIBarButtonItem(image: leftItem, style: .done, target: self, action: #selector(leftAction))
    self.navigationItem.rightBarButtonItem = rightButton
    self.navigationItem.leftBarButtonItem = leftButton

UsersController long press:

    @objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) {      
    let longPress = longPressGesture.location(in: self.usersTableView)
    usersTableView.allowsMultipleSelection = true
    let indexPath = self.usersTableView.indexPathForRow(at: longPress)
    
    UINotificationFeedbackGenerator().notificationOccurred(.success)        
    
    if indexPath == nil {
        print("Long press on table view, not row.")
        
    }
    else if (longPressGesture.state == UIGestureRecognizer.State.began) {
        print("Long press on row, at \(indexPath!.row)")
        
        if !previousIndexPath.isEmpty {
        }
    }
    
    if let selectedIndexPath = self.usersTableView.indexPathForSelectedRow {
        self.usersTableView.deselectRow(at: selectedIndexPath, animated: true)
    }
    
    userLabel.text = "Select"
    usersNumber.text = "0"
    plusButton.isHidden = true
}
1

There are 1 best solutions below

0
K N Sarvaiya On

You have to reset navigation leftBarButtonItem after updating the image.

S1 : declare variable in ViewController.

var leftBarBtnItem = UIBarButtonItem()

S2 : Set initial image and configure action.

leftBarBtnItem = UIBarButtonItem(image: leftItem, style: .done, target: self, action: #selector(leftAction))
self.navigationItem.leftBarButtonItem = leftBarBtnItem

S3 : In your gesture recognizer at the end of method update the image and reset left bar button item of navigation.

@objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) {
//at the end add below code, once done you can remove DispatchQueue
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.leftBarBtnItem.image = UIImage(named: "test2.png")
            self.navigationController?.navigationItem.leftBarButtonItem = self.leftBarBtnItem
        } 
}