Swift Change UIButton text
How to in Swift change UIButton text?
A common mistake, also done by myself some time ago, is to try to change it through an IBAction. You can use an IBAction, but probably not the way you think. A common mistake is to do something like this:
button.text = "Some text"
This will give a compiler error if you try something like that. I would make sense to be able to do it like that. Like in Visual Studio you can change text like that.
I’ll show you two methods on how you can change your UIButton text programmatically.
Swift Change UIButton text – Method 1 (IBOutlet)
In the first method, we will use an IBOutlet to change the button text. First, create a UIButton somewhere on the storyboard. Second, create the IBOutlet the normal way. Call the IBOutlet “button”. And you should end up with something like this:
@IBOutlet weak var button: UIButton!
Now in the viewDidLoad function, we will try to set a new title for the button. Try put in this into the viewDidLoad function:
button.setTitle("Ready", forState: .Normal)
If you try to run your code in the simulator now, your app will start up with the button called Ready. The text from the storyboard should never even appear in your app. I have pasted the complete source code from the example below.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
button.setTitle("Ready", forState: .Normal)
}
}
Swift Change UIButton text – Method 2 (IBAction)
Some might tell you that you can not change the UIButton text without an IBOutlet. In some cases, it might be more practical to use an IBOutlet, if your button should change text without any user interaction. If you want the text to change after the user clicked the button, the IBOutlet is not needed. You can do that from the IBAction directly. Here is how.
In your example create an IBAction for your UIButton. Notice the first word in the parenthesis. It says sender, or at least it should say. That sender represents the UIButton. And you can use the same setTitle function directly with the sender. Check out this example.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buttonClicked(sender: AnyObject) {
sender.setTitle("Sender", forState: .Normal)
}
}
Try to run that example an see what happens. As soon as you click the button, the text will change to “Sender”.
That is how you in Swift change UIButton text.
Check out UIButton in the swift documentation here https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/
See how to do it on video
Happy texting!