Jeppe Christensen Jeppe Christensen - 1 year ago 122
Swift Question

Set button text inside action

I have a button in which i want to set the text programatically.

as for right now i have the following:

@IBAction func saveButtonClicked(_ sender: AnyObject) {
sender.setTitle("Action", for: UIControlState.normal)

the issue is, that this is an action outlet, so the text only appends to the button when i press it..

I tried to put the setTitle inside the viewdidload function, but it wont compile.
How do i make the text constant? do i have to make multiple outlets, or can it be done in another way?

Answer Source

First create an Outlet named button_1.

@IBOutlet var button_1: UIButton!

Add this in viewDidLoad

button_1.setTitle("Button text", forState: .Normal)

To fire an action when button is clicked use this:

 @IBAction func ButtonClicked(sender: UIButton){
        button_1.setTitle("You clicked me", forState: .Normal)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download