UIButton setTitle doesn't work - swift

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

Swift 4:
Plain Title
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)
}
Attributed Title
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)

I just had a similar issue, and none of the answer here worked in my case.
For me the solution was to call button.layoutSubviews() to update UIButton's label just after i changed the title.
(also I had to change the button type to custom, otherwise the title change would blink)

Related

Button title does not show up

I got a UIButton with a background-image and a title. Wenn it's pressed (and holding), I should change it's background-image (WHICH DOES WORK), but keep it's title. But when I press the button, the title disappears and even when released, it also doesnt shop up again.
#IBAction func holdingTheButton(_ sender: Any) {
numberButton.setImage(UIImage(named: "buttonIn.png"), for: .normal)
numberButton.setTitle("Refuel", for: .normal)
}
This is a part of my holdingTheButton function (already declared/ initialized the button etc.), where I try to keep the title "Refuel". Btw: Changing to "for: .highlighted" or "for: .selected" doesnt change anything.
Screenshot of my Buttons configuration
When you press the UIButton it state is changed to highlighted when it's clicked. UIButton has different states such as selected, normal, highlighted and more.
If you would like the image and the title to stay the same you have got to call again "setTitle" and "setImage" for state "highlighted"
In your "ViewDidLoad" do the following:
numberButton.setImage(UIImage(named: "buttonIn.png"), for: .normal)
numberButton.setTitle("Refuel", for: .normal)
numberButton.setImage(UIImage(named: "buttonIn.png"), for: .highlighted)
numberButton.setTitle("Refuel", for: .highlighted)

how to change bordercolor when Button.isHighlighted

I wonder how I get my border around my UIButton to change opacity together with the text inside it, when it is either clicked or highlighted.
My logic tells me, that it should be something like this.. but it doesn't seem to work:
//BTN STYLING
btnstd.layer.cornerRadius = 5
btnstd.layer.borderWidth = 1.5
btnstd.layer.borderColor = UIColor.white.cgColor
//Change bordercolor when highlighted
if(btnstd.isHighlighted) {
btnstd.layer.borderColor = UIColor(white:1,alpha:0.3).cgColor
}
This is by the way put inside my ViewDidLoad() function
The actions you are looking for are .touchDown and anything .touchUp:
override func viewDidLoad() {
super.viewDidLoad()
theButton.setTitle("Normal", for: .normal)
theButton.setTitle("Highlighted", for: .highlighted)
theButton.layer.borderColor = UIColor.red.cgColor
theButton.layer.borderWidth = 1
theButton.addTarget(self, action: #selector(startHighlight), for: .touchDown)
theButton.addTarget(self, action: #selector(stopHighlight), for: .touchUpInside)
theButton.addTarget(self, action: #selector(stopHighlight), for: .touchUpOutside)
}
func startHighlight(sender: UIButton) {
theButton.layer.borderColor = UIColor.green.cgColor
theButton.layer.borderWidth = 1
}
func stopHighlight(sender: UIButton) {
theButton.layer.borderColor = UIColor.red.cgColor
theButton.layer.borderWidth = 1
}
It depends on what you are trying to do.
Case #1: You want this change to happen when the button is highlighted, but in a normal state have a different set of properties.
let theButton = UIButton()
// set common properties and layout code
theButton.setTitle("Normal", for: .normal)
theButton.setTitle("Highlighted", for: .highlighted)
In addition, you have setTitleColor(), setAttributedTitle, setTitleShadowColor(), setImage(), and setBackgroundImage() that you can code directly.
Border color in this case would need a subclass (not an extension, you want public properties) where you will check self.layer.hitTest() after wiring up a tap gesture on self.
Case #2: You want the button state to change when clicked, and stay changed.
You are part way there. If you supply the button in IB, make sure you add an IBAction for event touchUpInside. If you are working in code, here's the Swift 3 syntax.
theButton.addTarget(self, action: #selector(changeButton), for: .touchUpInside)
func changeButton(sender: UIButton) {
sender.setTitle("New Title", for: .normal)
sender.layer.borderColor = UIColor.red.cgColor
}
My preference (but only that) is to more strongly-type the sender (I think that's the correct term) for my actions. I'm sure there are pros and cons for using a specific sender (like UIButton) over AnyObject, but in this case I think the biggest reason is you don't need to force-cast the sender to UIButton.

Changing image for UIButton on button tap

I am creating a custom button which (almost) works fine. It is supposed to change it's image when the button is pressed down, and the change back again when you let loose. The problem is that it takes one click before it starts working.
#IBOutlet weak var myButton: UIButton!
#IBAction func myButton(sender: UIButton) {
myButton.setImage(UIImage(named: "myImage.png")!, forState: .Normal)
myButton.setImage(UIImage(named: "myImagePressed.png")!, forState: .Highlighted)
myButton.setImage(UIImage(named: "myImagePressed.png")!, forState: .Selected)
}
Since you've put your code to the IBAction, it only gets executed once the button is pressed. It is also unecessarily called every time the button is pressed. You need to run that code before the button is pressed. The best place is probably viewDidLoad() of the viewcontroller that controls the view the button is part of.

Referencing a UIButton by tag value

I am aware that a pushed button can be updated by reference to sender.
However I want to access a button from the program body by reference to its tag and then update its label,if that is possible.
Suggestions on how to do this (in Swift) would be appreciated.
To get a button inside a view using its tag, you can use the UIView.viewWithTag function.
if let button = self.view.viewWithTag(tag) as? UIButton
{
button.setTitle("newTitle", forState: UIControlState.Normal)
}
You have to use viewWithTag
ex:
var button = self.view.viewWithTag(tagNumber) as UIButton
button.setTitle("Button Title", forState: UIControlState.Normal)
Set the tag for all buttons. Then have a property
var buttons = [UIButton]
and in your awakeFromNib init it
buttons.append[myButtonWithTag0]
buttons.append[myButtonWithTag1]
// etc
Now you can access your buttons via
let button = buttons[index]
Swift3 : Possible with viewWithTag(button_tag) as:
let tmpButton = self.view.viewWithTag(tag) as? UIButton
tmpButton?.setTitleColor(.red, for: .normal)
tmpButton?.setTitle("Button Title", for: .normal)

Changing color of button text and state

I need to change the color of my button's text.
I also need to change the state to Disabled after the user presses it.
I have no idea how to do this. I've been looking things up for a while but they're all either in objective C or I can't understand it (usually help docs, they're stupid.).
In swift you change color for a specific State with the setTitleColor method.
In you case it will be :
button.setTitleColor(UIColor.grayColor, forState: UIControlState.Normal)
Swift 5 Update:
button.setTitleColor(UIColor.grayColor, for: UIControl.State.normal)
To change color of text
button.titleLabel.textColor = UIColor.grayColor()
To change state, on button press add following -
button.enabled = true
IBAction method should be like -
#IBAction func buttonTapped(sender : UIButton!) {
sender.enabled = false
}
Swift 3
button.setTitleColor(UIColor.gray, for: UIControlState.normal)
Note that;
grayColor has been renamed to gray
Normal is now normal (lowercase)
You have to set the text colour for the specific button state.
For Swift3, try below code :
#IBAction func butnClicked(sender : UIButton) {
sender.setTitleColor(.red, for: .normal)
sender.isEnabled = false
}
Set Enabled and text color from story board.