Jeppe Christensen
Jeppe Christensen

Reputation: 1890

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)
    closeKeyboard()
}

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?

Upvotes: 1

Views: 71

Answers (2)

Tuc3k
Tuc3k

Reputation: 1032

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)
    }

Upvotes: 1

Ishika
Ishika

Reputation: 2205

You can either draw IBOutlets to the button in order to set its title.

btnOutlet.setTitle("yourTitle", forState: .Normal)

Also, you can set tag to your button from storyboard, access it in the viewDidLoad() and then set its title as follows :-

 let btn:UIButton = self.view.viewWithTag(500) as! UIButton
 btn.setTitle("yourTitle", forState: .Normal)

Upvotes: 1

Related Questions