How to change the background color of an UIButton? - swift

I'm trying to do something seamingly simple, change an UIButton's background for aesthetic purposes... but I cannot find a background property because every other button seems to be clear (Not have an explicit background colour )
func updateNewButton() {
if newButton == true {
let buttonFont = self.ButtonFont
self.subscribeButton.SetAttributedTitle(title: StoreKit.sharedInstance.ButtonStateText, withFont: buttonFont, textColor: storeBackground, for: .normal)
}

To change the background color of your UIButton:
self.subscribeButton.backgroundColor = .yourDesiredColor
To change the background color of the titleLabel of your UIButton:
self.subscribeButton.titleLabel?.backgroundColor = .yourDesiredColor

Related

borderColor of a UIButton doesn't respect overrideUserInterfaceStyle

I ran into an issue I'm having trouble explaining. I have a simple UIButton for which I set the following properties:
class SecondaryButton: AppButton {
override func awakeFromNib() {
super.awakeFromNib()
cornerRadius = frame.height / 2
borderWidth = 2
borderColor = .formedText.withAlphaComponent(0.2)
}
}
.formedText access a namedColor that is supposed to be black in light mode and white in dark mode (I am not using .label because that isn't pure white or pure black on macOS Catalyst).
static let formedText = UIColor(named: "Formed Text")
This button is used in a page where I tried overriding the userInterfaceStyle in several places by calling overrideUserInterfaceStyle = .light
on the entire window
on the view controller
on the button itself
So here's the question: As you can see the button has a white border, even though the named colour is supposed to be black when userInterfaceStyle is light. If I set the exact same colour as the background of the same button by calling backgroundColor = .formedText.withAlphaComponent(0.2) it works just fine (i.e. the background is black with alpha 0.2).
Setting the color to something not affected by dark mode (such as .black or .red) works fine.
What am I missing here?
Please let me know if any further details are needed, and thanks in advance for any hints.
borderColor is a cgColor which is not adaptive.
You can handle the appearance change and update the border color inside the traitCollectionDidChange function:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
// Set the color again here if needed 👈
}
}
More information here

How can I change my custom cell background when pressing a button?

I have a CollectionView and a Button inside of an UIView. The purpose of the button is change the theme of the app, and I can change all colors, except for the backgroundColor of a nameContainerView on my TatodexCell (a custom cell).
I can't figure out how to access that property, and then, change the color I want.
THE FOLLOWING CODE IS LOCATED ON MY TatodexController FILE
My button property is:
let buttonChangeTheme: UIButton? = {
let button = UIButton()
button.setTitle("Change to blue theme", for: .normal)
button.addTarget(self, action: #selector(themeButtonClicked), for: .touchUpInside)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.layer.borderWidth = 3
button.layer.borderColor = Colors.mainBlack?.cgColor
button.backgroundColor = Colors.darkBlue
button.tintColor = Colors.mainWhite
return button
}()
My button-func is this one:
#objc func themeButtonClicked() {
clickCheck = !clickCheck
if clickCheck {
navigationController?.navigationBar.barTintColor = Colors.lightBlue
collectionViewPokemon?.backgroundColor = Colors.darkBlue
buttonChangeTheme?.backgroundColor = Colors.darkRed
buttonChangeTheme?.setTitle("Return to red theme", for: .normal)
}
else {
navigationController?.navigationBar.barTintColor = Colors.lightRed
collectionViewPokemon?.backgroundColor = Colors.darkRed
buttonChangeTheme?.backgroundColor = Colors.darkBlue
buttonChangeTheme?.setTitle("Change to blue theme", for: .normal)
}
}
THE FOLLOWING CODE IS LOCATED ON MY TatodexCell FILE
The nameContainerView I wanna modify it's bg color is:
lazy var nameContainerView: UIView = {
let nameView = UIView()
nameView.backgroundColor = Colors.lightRed
nameView.addSubview(nameLabel)
nameLabel.center(inView: nameView)
return nameView
}()
My goal is to change nameView.backgroundColor = Colors.lightRed to nameView.backgroundColor = Colors.lightBlue, but I can't access that property.
I would really appreciate any help or advice. Perhaps the solution is hiding in plain sight, but I've tried many ways and none of them worked. Let me know if another chunk of code is needed to be shown.
If you implement the tintColorDidChange() method in your custom collection view cell, and in that method, you set the cell's background color to the tint color, then when you change the owning UICollectionView's tint color, the cells's tintColorDidChange() methods will fire and you'll see the change.

UISegmentControl do not want fade when disabled

I have a Swift 4 UISegmentControl and I do not want it to fade when disabled.
anyone know how to stop if from fading?
tried this suggestion ... this changes the color ok, BUT is still faded
for view in mySegment.subviews {
view.tintColor = UIColor.blue
}
tried this suggestion ... changes color of text only for unselected AND it is still faded
let titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.blue]
mySegment.setTitleTextAttributes(titleTextAttributes, for: .disabled)
I want to set the color and NOT have the color fade

The title of my UIButton with UIVibrancyEffect is not visible when backgroundColor is assigned

I have two buttons added to UIVisualEffectViewwith effect UIVibrancyEffect:
let vibrancyEffectView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: UIBlurEffect(style: .Dark)))
vibrancyEffectView.contentView.addSubview(rightActionButton)
vibrancyEffectView.contentView.addSubview(leftActionButton)
the nest is set Title for them:
rightActionButton.setTitle(rightAction.title, forState: .Normal)
leftActionButton.setTitle(leftAction?.title, forState: .Normal)
And backgroundColor:
leftActionButton.backgroundColor = UIColor.clearColor()
rightActionButton.backgroundColor = UIColor.whiteColor()
Why I cannot see the right title? How to fix this?
Below is example from Apple, exactly what I need to do:
Is it possible?
Just set a backgroundColor with alpha component.
let vibrancyEffectView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: UIBlurEffect(style: .Dark)))
leftActionButton.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.2)
rightActionButton.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.2)
And the result is following:
The title is there but you cannot see it because it has the same color as it background. To use UIVibrancyEffect button background color must be set to clear color so this way all transparent pixels that are multiply with their corresponding background pixels will result in transparent as well. To fix this:
rightActionButton.backgroundColor = UIColor.clearColor()

Hide UIButton title

I have several UIButtons in a scrollview which I use in order to pass certain information. The information is saved in the title of each uibutton and when the button is clicked, it passes its title into the function.
All I want to do is hide the title of the button so you can not see the button. I have them overlaid over images which I use to show buttons. I have the text set to transparent but it still turns white when it is being clicked.
If you include code in your explanation, please explain where it should go.
After IOS7, If you want to just hide the title on titleLabel of a button you can do as follow. This way the title is still there it just makes it invisible. if you do NSLog("%#",button.currentTitle) you will see the title in terminal. Hope this helps.
[button setTitle:#"Button Title" forState:UIControlStateNormal];
button.titleLabel.layer.opacity = 0.0f;
I found only one correct working way:
//hide
yourButton.setTitleColor(UIColor.clearColor(), forState: .Normal)
//show (put your color)
yourButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
using button.titleLabel.hidden = YES will not work (at least on on iOS 7).
I ended up using:
// remove the button since hiding it doesn't work
[button.titleLabel removeFromSuperview];
// put back when you're done
[button addSubview:button.titleLabel];
You can hide the label inside the button:
button.titleLabel.hidden=YES;
or set the button's title to #"" and save the value somewhere else when you want to retrieve it.
I create a subclass of UIButton and override layoutSubviews method. Hiding titleLabel in layoutSubviews method works.
public class LoadingButton: UIButton {
public var isTitleHidden: Bool = false {
didSet {
titleLabel?.isHidden = isTitleHidden
}
}
public override func layoutSubviews() {
super.layoutSubviews()
titleLabel?.isHidden = isTitleHidden
}
}
if wanna hide titleLabel, just set isTitleHidden = true
I could not remove the title from the titleLabel nor the whole view as I needed it for constraints.
I ended up using
isEnabled = false
titleLabel?.layer.opacity = 0
setTitleColor(.clear, for: .disabled)
to hide the title and
isEnabled = true
titleLabel?.layer.opacity = 1
setTitleColor(titleColor(for: .normal), for: .disabled)
to show it again
To hide a title temporary just setTitle to empty string
setTitle("", for: .normal)
the button title label will be hidden but the title will still in the titleLabel, you can return it back using
setTitle(titleLabel?.text, for: .normal)
If you want to temporary hide the title, while you disabling the button, use:
setTitle("Title", for: .normal)
setTitle("", for: .disabled)
Then, button.isEnabled = false, when you want to hide the title.
I got a problem with title, because used an attributed title and nothing above helped. Then i found a workaround:
button.titleEdgeInsets = .init(top: 0, left: shouldHide ? 1000 : 0, bottom: 0, right: 0)
However it has some disadvantages, but fit my needs.
I've come up with this solution, which allows you to set title label text and use it with button image without showing it and not moving button image to the left.
- (void)hideButtonLabel:(UIButton*)buttonInp {
buttonInp.titleLabel.layer.opacity = 0.0f;
uttonInp.titleLabel.font = [UIFont fontWithName:#"Helvetica-Light" size:0.0];
}
You cannot hide UIButton titleLabel using .hidden property. Instead you can do this.
To Hide:
[self.yourButton setTitle:nil forState:UIControlStateNormal];
To Show:
[self.yourButton setTitle:#"Your Text" forState:UIControlStateNormal];
In Swift-
You don't need to hide nor need to make the opacity to 0.0. Swift gave you a simpler way.
Just set the title as nil. In fact, I got the idea from the documentation.
Command click on the setTitle(_:for:) method and you will see-
open func setTitle(_ title: String?, for state: UIControl.State) // default is nil. title is assumed to be single line
So, I just set it to nil.
setTitle(nil, for: .normal)
Swift 5 to hide button label:
myButton.titleLabel?.isHidden = true
Here myButton is a #IBOutlet of the button.