How do I change the image of a button when tapped - Swift - ios

I’m trying to change the image of a button when tapped (it’s for an audio player that I want Play to change to Pause). So far I’ve only managed to change it when the button is held, then it changes back when released.
I’ve tried using Selected instead of Highlighted but that doesn’t work. (The initial image is set in the Attributes Inspector). This is what I have -
#IBAction func buttonTapped(sender: AnyObject) {
ColourTestButton.setImage(UIImage(named: "blank-purple.jpg"), forState:.Highlighted)
}
I realise Highlighted means just that though on another image where I wanted it to change back (in a Cell of a Table View) it stayed, which is why I thought it would work for this one. What do I have to do here to make it stay changed to the new image?

I think you need this code:
#IBAction func buttonTapped(sender: AnyObject) {
let image = UIImage(named: "blank-purple.jpg") as UIImage!
let playButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
ColourTestButton.setImage(image, forState: .Normal)
}
UPDATE:
If you want to change the image like play/pause then you can do it this way:
var pressed = false
#IBAction func pressed(sender: AnyObject) {
if !pressed {
let image = UIImage(named: "pauseImage.png") as UIImage!
let playButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
btn.setImage(image, forState: .Normal)
pressed = true
} else {
let image = UIImage(named: "playImage.png") as UIImage!
let playButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
btn.setImage(image, forState: .Normal)
pressed = false
}
}

I think you are updating the image only at Highlighted state, so when you release the button it goes back to an original image. Try to change it at Normal state so that it will change the image. Take one flag to check the Play and Pause condition.
#IBAction func buttonTapped(sender: AnyObject) {
if (!flag)
{
//for Play
flag = true
ColourTestButton.setImage(UIImage(named:"USE PLAY IMAGE"), forState:. Normal)
}
else
{
//for Pause
flag = false
ColourTestButton.setImage(UIImage(named:"USE PAUSE IMAGE"), forState:. Normal)
}
}

Though Dharmesh Kheni's answer is OK I would recommend to use two buttons. You can set them in separate function or in interface builder and then just show and hide them according to state. Something like this:
func setButtons()
{
playBtn.setImage(UIImage(named: "play.png"), forState:.Normal)
pauseBtn.setImage(UIImage(named: "play.png"), forState:.Normal)
pauseBtn.hidden = true
}
#IBAction func playTapped(sender: AnyObject)
{
playBtn.hidden = true
pauseBtn.hidden = flase
//do other stuff
}
#IBAction func pauseTapped(sender: AnyObject)
{
playBtn.hidden = false
pauseBtn.hidden = true
//do other stuff
}

Related

border color is not changed

I want to change the borderColor and titleColor synchronized. but it didn't change the border color.
How can I make setTitleColor func applied to the border Color?
func setColor(button: UIButton) {
button.setTitleColor(UIColor.fromRGB(95, 61, 196), for: .selected)
button.layer.borderColor = UIColor.fromRGB(95, 61, 196).cgColor
}
#objc func handleCleaningKinds(_ sender: UIButton) {
setColor(button: sender)
deselectAllButtons()
sender.isSelected = true
}
func deselectAllButtons() {
for subView in stackView.subviews{
if let button = subView as? UIButton {
button.isSelected = false
//button.layer.borderColor = UIColor.white.cgColor
}
}
}
borderColor doesn't work with UIButton selectedState, So you need to handle that by himself based on your button's current state.
So write function like this to update state:
func updateSelectedState(_ isSelected: Bool) {
button.layer.borderWidth = isSelected ? 1 : 0 // If need to hide border on normal state
button.layer.borderColor = isSelected ? UIColor.fromRGB(95, 61, 196).cgColor : UIColor.white.cgColor // If need another color on normal state
button.isSelected = isSelected
}
Then your two functions should be like this:
#objc func handleCleaningKinds(_ sender: UIButton) {
deselectAllButtons()
updateSelectedState(sender)
}
func deselectAllButtons() {
for subView in stackView.subviews{
if let button = subView as? UIButton {
updateSelectedState(false)
}
}
}
Also setting color func setColor(button: UIButton) should not be called each time when button clicked, so you can call this function at viewDidLoad or any other function, where you create buttons.
You can try to add:
button.layer.borderWidth = 1
This might do the trick.
Have you tried adding these 2 lines?
button.layer.masksToBounds = false
button.clipsToBounds = true

Highlighting a button that gets pressed and unhighlighting the non pressed buttons SWIFT

I have three buttons that connect to the same IBAction. They all have their own out looks.
I found out how to make the button become highlighted when they are pressed and unhighlighted when the user presses another button. Is their a better way to write the code? Here is what I am using:
#IBAction func tipChanged(_ sender: UIButton) {
zeroPCTButton.isSelected = false
tenPCTButton.isSelected = false
twentyPCTButton.isSelected = false
sender.isSelected = true
}
The reason why I am asking is because I could make an application that has a thousand buttons and I don't want to brute force statements a thousands times
We can unhighlight the non pressed UIButton in the following way,
#IBAction func buttonAction(_ sender: Any) {
let the_tag = (sender as AnyObject).tag;
let button = self.view.viewWithTag(the_tag!) as? UIButton
button?.isSelected = true
button?.backgroundColor = UIColor.white
button?.setTitleColor(UIColor.black, for: .normal)
// Create a list of all tags
let allButtonTags = [1, 2, 3, 4, 5]
let currentButtonTag = (sender as AnyObject).tag
allButtonTags.filter { $0 != currentButtonTag }.forEach { tag in
if let button = self.view.viewWithTag(tag) as? UIButton {
// Deselect/Disable these buttons
button.backgroundColor = #colorLiteral(red: 0.80803, green: 0.803803, blue: 0.805803, alpha: 1)
button.setTitleColor(UIColor.darkGray, for: .normal)
button.isSelected = false
}
}
}
Let's Imagine you have 1000 buttons, You need to Implement some loop to do all the action related Button (Create,Add constraints, click events).Create UIButton Array for store your buttons.
var buttons:[UIButton] = []
Add buttons to this array when you create buttons
for buttonIndex in 1...1000 {
// your other stuff to create, add constraints to button
button.tag = buttonIndex
buttons.append(button)
}
Now you can easily achieve your object.
#IBAction func tipChanged(_ sender: UIButton) {
buttons.forEach({$0.isSelected = $0.tag == sender.tag})
view.layoutIfNeeded()
}

tap to select uibutton then tap to deselect uibutton

Hi I am trying to implement the following
tap uibutton to select and highlight background then tap the same button again to deselect the uibutton background to original state or another color
my code is as follows:
#IBOutlet weak var case4Btn: UIButton!
#IBAction func case4BtnClicked(sender: AnyObject) { //touch up inside
case4Btn.backgroundColor = UIColor.cyanColor()
}
#IBAction func case4BtnCancel(sender: AnyObject) {
case4Btn.backgroundColor = UIColor.lightGrayColor()//touch down
}
with the following code when I tap once it selects and highlights the UIButton button when i tap again it changes color buton does not deselect, in order for me to deselect I have to tap,hold and drag away from the button for it to change color or return to original state
Please help as this is driving me mad, something that seems to be so simple seems to be so hard
Thank you in advance
Solution 1
Set button's both/all state's color, text, text color either from code or from InterfaceBuilder as below
button.setBackgroundImage(UIImage(named: "cyanColorImage"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "brownColorImage"), forState: .Selected)
and handle the target and change the button's state only
#IBAction func buttonClickedHandle(sender: UIButton)
{
sender.selected = !sender.selected
}
Solution 2
You can do this with no extra variable. To achieve this
You can use button's selected property to achieve your requirement.
You can also handle button style with the single property.
You will not required to write separate method for all the button you need. Just write single method for all.
#IBAction func buttonClickedHandle(sender: UIButton)
{
if sender.selected
{
sender.backgroundColor = UIColor.cyanColor()
}
else
{
sender.backgroundColor = UIColor.lightGrayColor()
}
sender.selected = !sender.selected
}
Add all your button's target to buttonClickedHandle and access that particular button as sender. You are doing same task for all your button then why not reuse the code as explained.
All the best!
For 1 Button
var buttonState = "cyan"
//the color the button should be when pressed
#IBOutlet weak var case4Btn: UIButton!
//the button
#IBAction func case4BtnClicked(sender: AnyObject) {
//touch up inside
if(buttonState == "cyan"){
//if the button is supposed to be cyan
case4Btn.backgroundColor = UIColor.cyanColor()
//set the background color
buttonState = "gray"
//set it to be gray next time
}
else{
//if it isn't
case4Btn.backgroundColor = UIColor.grayColor()
//set the background color
buttonState = "cyan"
//make it become cyan next time
}
}
For Multiple Buttons
var button1State = "cyan"
var button2State = "cyan"
var button3State = "cyan"
//the color the buttons should be when pressed
#IBOutlet weak var case4Btn1: UIButton!
#IBOutlet weak var case4Btn2: UIButton!
#IBOutlet weak var case4Btn3: UIButton!
//the buttons
#IBAction func case4Btn1Clicked(sender: AnyObject) {
//touch up inside
if(button1State == "cyan"){
//if the button is supposed to be cyan
case4Btn1.backgroundColor = UIColor.cyanColor()
//set the background color
button1State = "gray"
//set it to be gray next time
}
else{
//if it isn't
case4Btn1.backgroundColor = UIColor.grayColor()
//set the background color
button1State = "cyan"
//make it become cyan next time
}
}
#IBAction func case4Btn2Clicked(sender: AnyObject) {
//touch up inside
if(button2State == "cyan"){
//if the button is supposed to be cyan
case4Btn2.backgroundColor = UIColor.cyanColor()
//set the background color
button2State = "gray"
//set it to be gray next time
}
else{
//if it isn't
case4Btn2.backgroundColor = UIColor.grayColor()
//set the background color
button2State = "cyan"
//make it become cyan next time
}
}
#IBAction func case4Btn3Clicked(sender: AnyObject) {
//touch up inside
if(button3State == "cyan"){
//if the button is supposed to be cyan
case4Btn3.backgroundColor = UIColor.cyanColor()
//set the background color
button3State = "gray"
//set it to be gray next time
}
else{
//if it isn't
case4Btn3.backgroundColor = UIColor.grayColor()
//set the background color
button3State = "cyan"
//make it become cyan next time
}
}
The only legitimate gesture is Touch Up Inside. Delete your other action entirely. Use a Bool property to keep track of which state the button is in. When it is tapped, use an if statement to change the button's background color according to the Bool property — and change the Bool property to match the new state.
#IBOutlet weak var case4Btn: UIButton!
var gray = true
#IBAction func case4BtnClicked(sender: AnyObject) { //touch up inside
if gray {
case4Btn.backgroundColor = UIColor.cyanColor()
} else {
case4Btn.backgroundColor = UIColor.lightGrayColor()
}
gray = !gray
}

How to programmatically add different actions and colours for on/off state to a Button

I have a button that I would like to use to show and hide a UIView. If you click the button, the UIView is shown. If you click again, the UIView should be hidden again.
This is the code I have:
super.viewDidLoad()
myView.hidden = true
#IBAction func myButton(sender: UIButton) {
myView.hidden = false
}
Adding to this, I'm looking to give the button a green color when it's tapped, and the normal blue when it's tapped again.
Simply toggle the hidden property:
#IBAction func myButton(sender: UIButton) {
// Toggle the view
myView.hidden = !myView.hidden
// Update the button color
if myView.hidden {
// make button blue
} else {
// make button green
}
}
I'm not fluent in Swift so I don't know the syntax to set the button's color but the above should point you in the right direction.
change
#IBAction func myButton(sender: UIButton) {
myView.hidden = false
}
to
#IBAction func myButton(sender: UIButton) {
myView.hidden = !myView.hidden
if myView.hidden {
sender.backgroundColor = UIColor.blueColor()
}else{
sender.backgroundColor = UIColor.greenColor()
}
}

How to change the background color of a UIButton when tapped in swift?

ViewController: UIViewController {
#IBAction func like(sender: AnyObject) {
like(backgroundColor!) = UIColor.greenColor()
}
}
I want to chanage the color of UIbutton"like button" :
White is the default "not tapped or unlike"
green when is tapped.
How do you change a buttons background colour when it is tapped using Swift?
The button isn't like -- that's the method's name. You can access the button through sender.
#IBAction func like(sender: AnyObject) {
(sender as UIButton).backgroundColor = UIColor.green
}
Or more concise:
#IBAction func like(button: UIButton ) {
button.backgroundColor = UIColor.green
}

Resources