-1

I added a today extension to my app. I edited the vanilla widget a little bit and made it look like this:

enter image description here

Please notice the UIButton titled "Went 1st". When it gets pressed (touched up inside to be exact), it triggers this action:

@IBAction func coinChanged(sender: UIButton) {
    if sender.titleLabel?.text == "Went 1st" {
        coin = true
        sender.titleLabel!.text = "Went 2nd"
    } else {
        coin = false
        sender.titleLabel!.text = "Went 1st"
    }
}

It basically alters between two states, changing its title and a variable accordingly.

Here is the problem though - when I press it, it indeed changes its title, but immediately changes it back, ending up on the same title as it had initially. My first thought was the action gets called twice after a press, but when I checked with print I found out it gets called only once. Sometimes the prints didn't even show up in console, but that's a different story.

So, that's one problem. There's one more, though - when I press the button, the whole widget gets misplaced. To know what I mean, look at the first picture (that's the widget before any presses) and now on this one (after the button gets pressed):

enter image description here

You can see that the borders are now on the very edge of TodayView. For reference, here are the constraints of the first segmented control:

enter image description here

Edit: Here are the constraints for "Went 1st/2nd" button: Edit 2: Be sure to tell me what's wrong if you downvote, so I can avoid making the same mistakes next time

enter image description here

Eugleo
  • 418
  • 4
  • 11
  • The second bug is very odd, are you setting any other button properties. – Alex Pelletier Jan 03 '16 at 10:35
  • No, nothing. I even deleted the button and made it from scratch, but it didn't help either. Also note, that no other button does it, only the "Went 1st". – Eugleo Jan 03 '16 at 13:21

1 Answers1

2

The problem is you should not be setting the button text like that. The title label is primarily used to set text size, font, color, etc. To set the title use something like this:

sender.setTitle("Button Title", forState: UIControlState.Normal)

So the new ib action should look like:

@IBAction func coinChanged(sender: UIButton) {
    if sender.titleLabel?.text == "Went 1st" {
        coin = true
        sender.setTitle("Went 2nd", forState: UIControlState.Normal)
    } else {
        coin = false
        sender.setTitle("Went 1st", forState: UIControlState.Normal)
    }
}
Alex Pelletier
  • 4,933
  • 6
  • 34
  • 58