无法在UINavigationItem中更改UIButton的标题

时间:2015-01-28 21:28:48

标签: swift ios8 uibutton uinavigationitem

在Swift for iOS 8中,我有一个使用UIView()作为其navigationItem的UIViewController。

该视图包含一个子视图 - 一个UIButton,我无法成功调用setTitle:forState:on

这是我的代码

playButton.setTitle("Play", forState: UIControlState.Normal)
playButton.tintColor = UIColor.grayColor()
playButton.titleLabel?.font = UIFont(name: "LucidaSansUnicode", size: 20)
playButton.addTarget(self, action: "playPressed", forControlEvents: UIControlEvents.TouchUpInside)        
playButton.setTranslatesAutoresizingMaskIntoConstraints(false)
transportBar.backgroundColor = UIColor.clearColor().colorWithAlphaComponent(0.0)
transportBar.addSubview(playButton)
transportBar.addConstraint(NSLayoutConstraint(item: transportBar, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: playButton, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0))
transportBar.addConstraint(NSLayoutConstraint(item: transportBar, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: playButton, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0))
navigationItem.titleView = transportBar

该按钮最初效果很好 - 设置了“播放”标题,调用了playPushed(),我可以在按钮上成功添加和删除目标。

为什么标题不变?

此外,当设备方向(和导航栏)旋转时,按钮的textLabel最终会自动更新!!在我更新按钮的标题后,是否有一些消息我可以发送到UINavigationController ????我试过self.navigationController?.navigationBar.setNeedsDisplay()

我已经尝试查看堆栈溢出,在setTitle:forState:call周围执行了诸如place enabled = false / true之类的操作。我记得在transportBar,self.view和navigationItem.titleView上尝试layoutSubviews()!

任何线索?谢谢你的帮助!

我的playPressed()函数已在下面添加,在TouchUpInside上触发:

func playPressed() {
    playButton.setTitle("Stop", forState: UIControlState.Normal)
    playButton.removeTarget(self, action: "playPressed", forControlEvents: UIControlEvents.TouchUpInside)
    playButton.addTarget(self, action: "stopPressed", forControlEvents: UIControlEvents.TouchUpInside)
}

1 个答案:

答案 0 :(得分:1)

我想,也许你的String会被UIButton本身的attributedString方法覆盖。尝试设置attributedString:

var attri = NSAttributedString(string: "Your String")
button.setAttributedTitle(attri, forState: UIControlState.Normal)