0

我有一些代码如下,它创建了一个条形按钮项,然后像许多应用程序一样添加到右侧的导航栏。

我遇到的问题是按钮/图像根本不显示。

我怎样才能解决这个问题?

仅供参考:在视图中运行的所有其他代码确实加载之后,此代码作为 setup() 函数运行。

        let image = UIImage(systemName: "paperplane")?.withTintColor(.black, renderingMode: .alwaysOriginal)
        
        let button = UIBarButtonItem(image: image,
                                     style: .plain,
                                     target: self,
                                     action: #selector(showDMController))
        
        self.navigationItem.rightBarButtonItem = button
4

2 回答 2

0

In your UIViewController class write this code in viewDidLoad() method

override func viewDidLoad() {
    super.viewDidLoad()
    let rightBarButton = UIButton(type: .custom)
    rightBarButton.contentMode = .scaleAspectFit
    rightBarButton.setImage(yourImage, for: .normal)
    rightBarButton.setImage(yourImage, for: .selected)
    rightBarButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(yourGestureRecognizer)))
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButton)
    navigationItem.rightBarButtonItem?.style = .plain
}

@objc func yourGestureRecognizer() {
   print("yourGestureRecognizer called")
}
于 2020-07-31T08:57:55.477 回答
0

试试这个经过测试并为我工作的代码。

let image = UIImage(systemName: "paperplane")?.withTintColor(.black, renderingMode: .alwaysOriginal)
    
    let button = UIBarButtonItem(image: image,
                                 style: .plain,
                                 target: self,
                                 action: #selector(showDMController))
    
    self.navigationController?.navigationBar.topItem?.rightBarButtonItem = button

我已添加topItem添加rightBarButton。如果这不能解决您的问题,请告诉我。

于 2020-07-31T04:32:01.400 回答