Changing image for UIButton on button tap - swift

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.

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)

Nav button needs to go form the last view to the first view

Hello, I have provided the link above to show a visual view of what I am trying to accomplish. So each button is a segue to the next view except the last button is not which is intended. The last two views with the back buttons at the top that are automatically included because of the nav controller I want to have those back buttons go to the first view controller. How can I do this either with xcode and swift?
If you want to remove all the navigation controller then use this code
Put this code in the button selector method
self.navigationController!.viewControllers.removeAll()
OR
navigationController?.popToRootViewController(animated: true)
OR
If you don’t have a Navigation Controller and use dismissViewController method, you still can use:
view.window?.rootViewController?.dismiss(animated: true, completion: nil)
Now comes the back button code:
override func viewDidLoad() {
super.viewDidLoad()
var backbutton = UIButton(type: .Custom)
backbutton.setImage(UIImage(named: "BackButton.png"), forState: .Normal) // Any image can be used. download back button image from any site or whatever you wanna use.
backbutton.setTitle("Back", forState: .Normal)
backbutton.setTitleColor(backbutton.tintColor, forState: .Normal) // You can change the TitleColor
backbutton.addTarget(self, action: "backAction", forControlEvents: .TouchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backbutton)
}
func backAction() -> Void {
//here put code from above whichever you wanna use for example I'm using one
self.navigationController?.popToRootViewController(animated: true)
}

How to write function which change button color

I have a small problem. I created a short quiz app, and when we choose the answer the answer is green. I need a function that will change all buttons to the basic color, blue
First you should have array with references for your buttons. If you use interface builder, you can create outlet collection
#IBOutlet var buttons: [UIButton]!
Then, when button is pressed, change color for each button depending on if element is equal to sender of action for button pressed event
#IBAction func buttonPressed(_ sender: UIButton) {
for button in buttons {
button.backgroundColor = button == sender ? .green : .blue
}
}

Swift UIButton not appearing on screen

I have a view in my tabbar controller where I would like to show a button. I create this button programmatically based of a condition, therefore I use the following code but nothing is appearing:
override func viewDidLoad() {
super.viewDidLoad()
if !Settings.getIsConnected() {
notConnected()
}
}
func notConnected() {
let connectBtn = UIButton(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 200, height: 45))
connectBtn.setTitle("Connect", forState: .Normal)
connectBtn.addTarget(self, action:#selector(self.pressedConnect(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(connectBtn)
print("Button created")
}
func pressedConnect(sender: UIButton!) {
}
I am clueless on what I am doing wrong. Anyone got suggestions? Cause it does print out "Button created" so it definitely runs the code inside the noConnected() method.
Add a background color to your UIButton and add a tint color to the title. This will resolve the problem
Try moving the code to viewDidAppear and see if the button is showing up.
The frame is not correctly set when in viewDidLoad. Use the method viewDidLayoutSubviews for the earliest possible time where the frame is correctly setup for a ViewController.
With this code change, you will need some additional logic for when your button should be added as a subview though.
A programmatically created button may not show up because of more reasons, e.g:
the tint color is not set
the background color is not set
the button is not added to the view hierarchy
the button is hidden
In your case, you should change the tint color or the background color of your button.
E.g.:
Swift 4.2:
private lazy var connectButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .green
button.setTitleColor(.black, for: .normal)
button.setTitle(NSLocalizedString("Connect", comment: ""), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(connectButton)
}
You can re-check the button properties in the storyboard that it is not hidden.

UIButton setTitle doesn't work

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)