每次在 UIKit 中录制导航栏 rightItem 时如何更新 UIButton

How to update UIButton in navbar rightItem each time when it is taped in UIKit

我使用自定义图像为导航栏创建了按钮,并希望在用户每次点击它时更改其色调。

 let addToFavoritesButton = UIImage(systemName: SystemImages.FilledStar.rawValue)
 navigationItem.rightBarButtonItem = UIBarButtonItem(image: addToFavoritesButton, style: .plain, target: self, action: #selector(addOrRemoveFromFavorites))
 navigationItem.rightBarButtonItem?.tintColor = presenter.addToFavoriteButtonColor()

您应该将 rightBarButtonItem 色调的更改放在您为点击 rightBarButtonItem 创建的函数中

   @objc func addOrRemoveFromFavorites(_ sender: AnyObject) {
   navigationItem.rightBarButtonItem?.tintColor = 
presenter.addToFavoriteButtonColor()
}

这只有在你有 UINavigationController 时才有效。