Reputation: 661
In Swift for iOS 8, I have a UIViewController using a UIView() as its navigationItem.
The view contains one subview - a UIButton, that I am unable to successfully call setTitle:forState: on
here is my code
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
The button works great initially - the "Play" title is set, playPushed() is getting called, and I can successfully add and remove targets on the button.
Why is the title not changing???
Also, when the device orientation(and the nav bar) rotates, the button's textLabel finally updates itself!! Is there some message I can send to the UINavigationController after I update the button's title???? I've tried self.navigationController?.navigationBar.setNeedsDisplay()
I've tried looking around stack overflow, done things like place enabled = false/true around the setTitle:forState: call. I remember trying layoutSubviews() as well on transportBar, self.view, and navigationItem.titleView!
Any clues? Thanks for your help!
My playPressed() function has been added below, triggered on 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)
}
Upvotes: 0
Views: 699
Reputation: 22343
I think, maybe your String will be overwritten by the attributedString
method of the UIButton itself. Try to set the attributedString:
var attri = NSAttributedString(string: "Your String")
button.setAttributedTitle(attri, forState: UIControlState.Normal)
Upvotes: 1