I'm trying to change the text of a UIButton when it gets clicked. I've tried the following things, which failed:
First I tried inserting a button on the storyboard and linking it to the view controller, with the code for the button appearing like this:
@IBAction func button(sender: AnyObject) {}.
Within the button's parentheses, I then used
button.setTitle ("something" , for State: .Selected)
However, when I run this code in the simulator, it doesn't seem to work at all.
I have also tried, following the Apple reference manual, to set different labels for different states in the side menu after clicking on said button, but still this didn't work. Can anyone tell me exactly (i.e. what code to write and where exactly it goes) how to make this happen?
The type of the sender should be UIButton, when creating the IBAction function. The sender is your button. The function is called when you tap on the button. You must use the function setTitle on the sender(your button).
@IBAction func buttonTouchedUpInside(sender: UIButton) {
sender.setTitle("buttonName", forState: .normal)
}
The setTitle()
method will work for titles that are "Plain" as defined in the button's Attributes inspector.
@IBAction func button(sender: UIButton) {
sender.setTitle("buttonName", for: .normal)
}
The setTitle()
method has no effect on a button's title if it's configured as "Attributed" in the Attributes inspector. To manage this situation, first get the attributed title from the button, then set the value.
@IBAction func button(sender: UIButton) {
let attributedTitle = sender.attributedTitle(for: .normal)
attributedTitle?.setValue("buttonName", forKey: "string")
sender.setAttributedTitle(attributedTitle, for: .normal)
}
In practically, if you use button from Storyboard or Xib file, and not clear button value in (Storyboard, Xib), than setTitle method doesn't work. If you cleared button value, setTitle method is work.
Create an IBOutlet for your button, then this code should work (assuming you named your IBOutlet button
):
button.setTitle("title", forState: .Normal)
button.setTitle("title 1", forState: .Application)
button.setTitle("title 2", forState: .Highlighted)
button.setTitle("title 3", forState: .Reserved)
button.setTitle("title 4", forState: .Selected)
button.setTitle("title 5", forState: .Disabled)
place it in your viewDidLoad()
method.
This worked for me.
dispatch_async(dispatch_get_main_queue(), ^{
[self.btnAssment setTitle:@"ASSDate" forState:UIControlStateNormal];
});
let button = UIButton()
button.setTitle("Button", for: .normal)
button.setTitleColor(.black, for: .normal)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With