swift 长按后更改leftBarButtonItem

gk7wooem  于 2022-12-02  发布在  Swift
关注(0)|答案(1)|浏览(120)

我需要在长按后更改leftBarButtonItem,我在TabBarController中设置了leftBarButtonItem,并在UsersController中设置了长按操作,如何才能做到这一点?
选项卡栏控制器:

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

用户控制器长按:

@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
}
biswetbf

biswetbf1#

您必须在更新图像后重置导航leftBarButtonItem。
S1:在ViewController中声明变量。

var leftBarBtnItem = UIBarButtonItem()

S2:设置初始图像并配置动作。

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

S3:在方法结束时,在手势识别器中更新图像并重置导航的左栏按钮项。

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

相关问题