Swift: Change colour of button when tapped - ios

I'm new to Swift and I'm trying to change the button colour on tap. When the button is tapped, it should change colour and when released it should go back to the original button colour.
An example of this is the calculator. When you tap a button, it changes from light grey to dark grey and when the user removes their finger off the button, it goes back to the original light grey colour. How do I go about doing that?
So far, I've only got this..
#IBAction func changeButtonColourOnTouch(sender: UIButton) {
zeroButton.backgroundColor = UIColor.blueColor()
}
The above code changes the button colour to blue but stays blue.

The problem is, after releasing the button, you should return the color to the original state.
You can link direct from storyboard, in the action TouchUpInside (release) and TouchDown (press) , to change the button color to the correct state in each event.
Or you can add a Target in the button by code, linking to the functions, as the code bellow shows it.
zeroButton.addTarget(self, action: Selector("holdRelease:"), forControlEvents: UIControlEvents.TouchUpInside);
zeroButton.addTarget(self, action: Selector("HoldDown:"), forControlEvents: UIControlEvents.TouchDown)
//target functions
func HoldDown(sender:UIButton)
{
zeroButton.backgroundColor = UIColor.blueColor()
}
func holdRelease(sender:UIButton)
{
zeroButton.backgroundColor = UIColor.whiteColor()
}
Code adapted by the present in the link UIButton with hold down action and release action

The checked answer above works, but if the user holds down on the button, then drags out, the background color won't return to normal. It's a tiny UI bug, but a simple fix. This includes the code of the checked answer.
zeroButton.addTarget(self, action: #selector(holdRelease), for: .touchUpInside);
zeroButton.addTarget(self, action: #selector(heldDown), for: .touchDown)
zeroButton.addTarget(self, action: #selector(buttonHeldAndReleased), for: .touchDragExit)
//target functions
#objc func heldDown()
{
zeroButton.backgroundColor = .blue
}
#objc func holdRelease()
{
zeroButton.backgroundColor = .white
}
#objc func buttonHeldAndReleased(){
zeroButton.backgroundColor = .blue
}

you could also use a tap gesture and change the color of the button as the user is tapping on the button
you could see apple documentation regarding UIGestureRecognizer in here
it is a little bit advanced, but you will learn a lot from it.

You can also use setbackgroundImageForState to define color image as button background for all UIControlState you are interested in e.g. Normal, Highlighted, Disabled, Selected.
let cx = UIGraphicsGetCurrentContext()
let color = UIColor.redColor()
let state = UIControlState.Selected
UIGraphicsBeginImageContext(CGSize(width:1, height:1))
CGContextSetFillColorWithColor(cx, color.CGColor)
CGContextFillRect(cx, CGRect(x:0, y:0, width:1, height:1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.zeroButton.setBackgroundImage(colorImage, forState: state)
Now color changes automatically and you don't have to handle it manually.

If you want that for a programmatically defined button, just declare the button of type system during its initialisation:
let button = UIButton(type: .system)

Related

how to add element using swift to a storyboard stackview

I am a beginner so sorry if it is a stupid question but I am trying to add new elements to a stack view that was made with a storyboard. I want to do it every time a button was pressed and I want the same color, size, constraint... how do I do this?
here is an image of my code
and this is the image of my storyboard structure
and this is what I made with the storyboard
and I want to add another button like the other ones every time the settings button is pressed
pls, can anyone help?
Connect your stack view to an #IBOutlet such as:
#IBOutlet var stackView: UIStackView!
Instead of trying to "copy" the button you designed in Storyboard, use a function to create a new button with your desired properties:
func makeNewButton() -> UIButton {
// create a button
let b = UIButton()
// set your desired font
b.titleLabel?.font = .systemFont(ofSize: 18.0, weight: .light)
// set background color to your desired light-green
b.backgroundColor = UIColor(red: 0.0, green: 0.85, blue: 0.0, alpha: 1.0)
// set title colors for normal and highlighted
b.setTitleColor(.white, for: .normal)
b.setTitleColor(.gray, for: .highlighted)
return b
}
Now, your function for tapping the "Settings" button could look like this:
#IBAction func settingsButtonPressed(_ sender: Any) {
// call func that returns a new button with your
// desired colors, font, etc
let newButton = makeNewButton()
// set the title (presumably you'll be getting a new title string from somewhere)
newButton.setTitle("New Button", for: [])
// give it an action
newButton.addTarget(self, action: #selector(self.btnTapped(_:)), for: .touchUpInside)
// add it to the stack view
stackView.addArrangedSubview(newButton)
}
Edit the above code assumed an existing function for handling the button action - such as:
#objc func btnTapped(_ sender: UIButton) {
// do something when the button is tapped
print("A button was tapped...")
}

UIButton not toggling between two images Swift 4.2

I am wanting to add sounds to my app. I have added a UIButton with two images, soundON and soundOFF.
When I call the sound settings in the app the first time, they toggle fine with each image.
However, when I return to the sound settings a second and subsequent time, it is like the soundOff images does not disappear when the soundOn image is displayed.
Odd as the code is so short and simple.
func soundButton() {
sounds = UIButton(frame : CGRect(x: 65, y: 70, width: 40, height:40))
sounds.setImage(UIImage(named : "soundON"), for : .normal)
sounds.setImage(UIImage(named : "soundOFF"), for : .selected)
sounds.showsTouchWhenHighlighted = true
sounds.addTarget(self, action: #selector(soundButtonTapped), for: .touchUpInside)
self.soundView.addSubview(sounds)
}
#objc func soundButtonTapped(_ sender: Any) {
sounds.isSelected.toggle()
isSoundOn.toggle()
}
I have added a video to show the issue as this will save a ton of typing.
http://www.reeflifeapps.com/soundError.mov
Any help is greatly appreciated.
update:
I had the button on a UIView that was hidden on startup of the puzzle. When the user pressed the "Sounds Settings" icon, the sound setting UIView was unhidden. I had the button on this func to unhide the sound settings. I moved it to viewDidLoad() and it fixed it.
I suggest you to define a boolean variable that keeps the current state of your button. Then, you should set current image of button according to the current state of the variable.
var isSoundOn = false
#objc func soundButtonTapped(_ sender: Any) {
isSoundOn.toggle()
if isSoundOn {
// your logic when sound on (set button selected image, action etc)
} else {
// logic when sound off (set button not selected image, action etc)
}
}
If you still want to use soundButton.isSelected as your boolean variable,do not define images for different states in soundButton.setImage(yourImage, for: .selected) and soundButton.setImage(yourImage, for: .normal) and define them as follows:
soundButton.setImage(soundButton.isSelected ? soundOnImage : soundOffImage, for: .normal)
One of those two approaches above can be used.
UPDATE:
As Lloyd Kaijzer stated, isSoundOn = !isSoundOn updated as isSoundOn.toggle()

UIButton change background when tapped (programmatically)

I have a custom UIButton but I am not able to make changing background or text color based on a quick tap. If something works, it's only on long press:
buton.isUserInteractionEnabled = true
buton.setTitle("text_normal", for: .normal)
buton.setTitle("text_highlighted", for: .highlighted)
buton.setTitle("text_selected", for: .selected)
buton.setTitle("text_focused", for: .focused)
The only text I can get is "text_highlighted" after holding the button ~1 second. But nothing happens on short tap.
But the action is triggered correctly:
let tap2 = UITapGestureRecognizer(target: self, action: #selector(handleTap))
buton.addGestureRecognizer(tap2)
#objc func handleTap(sender: UITapGestureRecognizer) {
print("click")
}
What I tried:
Adding custom
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
...
which is also triggered later. And combining with tocuhesEnded didn't change the color temporarily as well (maybe it was too quick).
I can't use UIButton(type: .system) as well - it's not system styled button.
Similar as with changing text this is not working as well:
self.setTitleColor(UIColor.gray, for: .normal)
self.setTitleColor(UIColor.yellow, for: .selected)
self.setTitleColor(UIColor.yellow, for: .highlighted)
self.setTitleColor(UIColor.yellow, for: .focused)
I can see yellow only when long pressed. I am looking for something like this, but it needs to work on quick tap as well.
Custom button is modifying layoutSubviews(), but not colors. Custom button contains default image and label. Whole button has rounded corners. But overall nothing special is in there.
I am not using any storyboard or XIB - everything is in Swift 4 programatically.
The button is supposed to lead to another ViewController, but I want to see the immediate feedback on click. Something like when created from storyboard: https://youtu.be/lksW12megQg?t=3m25s - not even simple alpha change works for me right now.
check isselected property of uibutton if button is selected then change the background color of button
Jen Jose was right - there was a problem with my parent class which was 'eating up' my touches. I confirmed this when moving it to different ViewController + I had the same issue with table, which couldn't handle touch events (https://stackoverflow.com/a/9248827/1317362)
EDIT:
To be precise - this button was in a UIScrollView.
Adding scrollView.delaysContentTouches = NO; solved the issue completely.
Details: https://stackoverflow.com/a/16650610/1317362

Swift UIButton Tint Text When Highlighted

In my app, I have a button with a text title next to a button that's an image. I want the color scheme of both buttons to match. I create the button with the image like this:
let button1 = UIButton()
button1.setImage(
UIImage(named: "button1")?.withRenderingMode(.alwaysTemplate), for: .normal)
button1.tintColor = UIColor.green
This creates the effect that I want on both buttons, i.e. the button is green, then when it's highlighted it gets tinted to a darker, black-ish green. I tried creating the text button the same way:
let button2 = UIButton()
button2.setTitle("button2", for: .normal)
button2.tintColor = UIColor.green
But, in this case, setting the tint color doesn't change the color of the button's title/text (it remains white even when highlighted). My solution to this is as follows:
let button2 = UIButton()
button2.setTitle("button2", for: .normal)
button2.setTitleColor(UIColor.green, for: .normal)
button2.setTitleColor(UIColor(red: 0x23 / 255.0,
green: 0x34 / 255.0,
blue: 0x16 / 255.0,
alpha: 1.0), for: .highlighted)
Essentially, I've estimated the color that the image gets tinted to when it's highligted and set the text color to match. This works fine, but it bothers me that I only have an approximation; ideally, I would want the system to tint the text color for me when the button is highlighted in the same way that it tints the image. I get that this is a really small problem and that fixing it probably won't noticeably improve the app, but I'd still like to know if there's a way to tint a button with a text title "automatically" (as opposed to hardcoding the tint).
Tint color is property of UIView, which doesn't have a state. State is property of UIControl(Button's parent class). Means that you cannot change the tint on the bases of button's state. You can only change properties mentioned seen in this screen shot on the basis of button's state by default.
Also the
darker, black-ish green
color your getting that the default behaviour of button to change background color to show highlighted state
Solution : CustomButton
Create a custom UIButton
class MyButton : UIButton {
override var isHighlighted: Bool{
didSet {
tintColor = isHighlighted ? UIColor.green : UIColor.red
// do additional work here according to your need
}
}
override var isSelected: Bool {
didSet {
// do changes according to you need
}
}
}
You can also set the properties mentioned in above image programmatically.
button.setTitleColor(UIColor.green, for: .normal)
button.setTitleColor(UIColor.red, for: .highlighted)
button.setBackgroundImage(yourBackgroundImage, for: .normal)
let button2 = UIButton()
button2.addTarget(self, action: #selector(self.pressed), for: [.touchDown])
button2.addTarget(self, action: #selector(self.released), for: [.touchDragExit, .touchUpInside, .touchUpOutside, .touchCancel])
func pressed() {
// set colour
}
func released() {
// set colour
}

Swift / how to change the color of the button text in a xib file

I have a xib file as custom menu.
I want to change the button's text color once the button has been pressed.
This is the code handling the tap:
let rulerMenu = (NSBundle.mainBundle().loadNibNamed("rulerMenu", owner: self, options: nil).last) as! RulerMenu
rulerMenu.frame = CGRectMake(self.view.bounds.size.width, 112, self.view.bounds.size.width, 48)
self.view.addSubview(rulerMenu)
rulerMenu.mmBtn.addTarget(self, action: #selector(ViewController.mmBtnFunc), forControlEvents: .TouchUpInside)
And that is the code I've started implementing as action for the button.
func mmBtnFunc() {
let rulerMenu = (NSBundle.mainBundle().loadNibNamed("rulerMenu", owner: self, options: nil).last) as! RulerMenu
rulerMenu.mmBtn.setTitleColor(UIColor.uIColorFromHex(0xFB61CF), forState: .Normal)
}
The color doesn't change at all.
I have tryed to add self.view.addSubview(rulerMenu) to the mmBtnFunc() function and then the menu popped of again with the color changed. But I don't want it to "re animate". I just want the color to change.
What am I missing? Help is very appreciated.
To solve your problem try this: an action target usually has an argument, so, try change your function prototype to this func mmBtnFunc(button: UIButton) and then change directly buttons's color. After this change you will need to update the action selector like this #selector(ViewController.mmBtnFunc(_:))

Resources