【问题标题】:Cant change title of UIButton in UINavigationItem无法更改 UINavigationItem 中 UIButton 的标题
【发布时间】:2015-01-28 21:28:47
【问题描述】:

在 iOS 8 的 Swift 中,我有一个 UIViewController 使用 UIView() 作为它的导航项。

视图包含一个子视图 - 一个 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: 调用周围完成了诸如 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)
}

【问题讨论】:

  • 但是您没有在代码中再次设置标题。正如您所说,您只需将标题设置为“播放”一次即可。
  • 是的,我在按下按钮时再次设置它。在添加和删除目标时,这确实有效
  • 请向我们展示你的 playPushed 方法。
  • 我已将它添加到我的问题中。有一个类似的 stopPressed() 函数

标签: swift ios8 uibutton uinavigationitem


【解决方案1】:

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

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

【讨论】:

  • 不,这没有成功...你看到我关于方向的最后评论了吗?
猜你喜欢
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多