2

How can attributes be modified from the sender in swift? For example, if I have a multiple buttons that are connected to the same event handler, how can I modify the attributes of the button (say, the title) that was pressed?

@IBOutlet weak var grade_preK: UIButton!

@IBAction func gradeButtonPressed(sender: AnyObject) {
    sender.title = "New Title"  
}

The handler here returns the error "Cannot assign to 'title' in 'sender'". How then, can attributes be changed on the sender of the event?

barrt051
  • 242
  • 3
  • 13

1 Answers1

2

When you created this, Interface Builder may have given you the option to declare sender to be UIButton rather than AnyObject (it does have that option; you may not have noticed it). You could have chosen that, or you can fix it now:

@IBAction func gradeButtonPressed(sender: UIButton) {

And now sender is of the right type so you can modify it (and it is reasonable style to do so in Cocoa).

(Note that UIButton actually has a setTitle(_ title: String?, forState state: UIControlState) method, not a setTitle() method, so that's what you probably meant to call.)

Rob Napier
  • 286,113
  • 34
  • 456
  • 610