0
votes

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)
}
1
But you don't set the title again in your code. You only set the title once to "Play" and that works, as you say.Christian
yes, I set it again in when the button is pushed. While adding and removing targets, which do in fact workDanMoore
Show us your playPushed-method please.Christian
I have added it to my question for you. There is a similar stopPressed() functionDanMoore

1 Answers

1
votes

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)