2017-07-27 69 views
0

我在viewDidLoad中有以下內容。它設置了一個自定義rightBarButtonItem(在自定義UINavigationBar)。UIBarButtonItem(customView :) - 不可打標

let button = UIButton() 
    let attrs = [NSFontAttributeName: UIFont(name: "Montserrat-Light", size: 14)!, NSForegroundColorAttributeName: UIColor.black] 
    let title = NSAttributedString(string: "Sign In", attributes: attrs) 
    button.setAttributedTitle(title, for: .normal) 
    button.addTarget(self, action: #selector(self.pushVcLogin), for: .touchUpInside) 

    let parentView = UIView(frame: button.bounds) 
    parentView.addSubview(button) 
    button.sizeToFit() 
    parentView.bounds = CGRect(x: 0, y: 0, width: button.bounds.size.width, height: button.bounds.size.height) 

    self.navItem.rightBarButtonItem = UIBarButtonItem(customView: parentView) 

自定義UIBarButtonItem看起來應該是它的樣子,但它不可點擊。

任何想法?

+0

你能分享「pushVcLogin」的代碼嗎? –

+0

「自定義UINavigationBar」是什麼意思?你是否使用'UINavigationController'?只是「自定義」的視覺外觀,還是使用獨立的導航欄? –

+0

對不起,我想通了 - 這整個視圖控制器是嵌套在UINavigationController中的(cue @ NicolasMiari的問題),並且該控制器(無形)將UINavigationBar疊加到包括我的自定義UINavigationBar在內的整個視圖上。 –

回答

1

所有,如果您的視圖層次首先有UINavigationController的

其次,你可以使用navigationItem並添加就可以了定製的UIBarButtonItem。

我剛剛檢查了下面的代碼,它的工作原理。

let button = UIButton()   
    let attrs = [NSFontAttributeName: UIFont(name: "Montserrat-Light", size: 14)!, NSForegroundColorAttributeName: UIColor.black] 
    let title = NSAttributedString(string: "Sign In", attributes: attrs) 
    button.setAttributedTitle(title, for: .normal) 
    button.addTarget(self, action: #selector(self.pushVcLogin), for: .touchUpInside) 

    let parentView = UIView(frame: button.bounds) 
    parentView.addSubview(button) 
    button.sizeToFit() 
    parentView.bounds = CGRect(x: 0, y: 0, width: button.bounds.size.width, height: button.bounds.size.height) 

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: parentView) 

此處還有故事板圖片navigationController和viewController的樣子。

enter image description here

相關問題