I am looking for a solution to this problem that does NOT require using images/PNGs. I am looking for a way to remove the UIButton's blue background color when it's in selected state, and I just cannot find a way to do that without using images. I am basically trying to do something like that in case of a UITableViewCell:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
I had this same issue and I resolve it by changing the UIButton type from "System" to "Custom". The blue background color does not show up in selected state when it is a "Custom" type.
Unfortunately I'm away from my test machine at the moment, but there are two things you could try.
First would be to set the following property:
button.adjustsImageWhenHighlighted = NO;
Or uncheck "Highlight adjusts image" in Interface Builder.
If that doesn't work like you expect it to, you can deselect the button in the action you tied it to, like so:
- (IBAction)yourButtonAction:(id)sender {
[sender setHighlighted:NO];
}
Change the alpha of the tintColor to zero, works if iOS is 5.0 or later
UIColor *color = [[UIColor alloc] initWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
button.tintColor = color;
Very simple, in storyBoard, select your UIButton and open attribute inspector. Now scroll down to View section and change Tint property to Clear Color or any specific color if u want.
UIButton also with custom type, we can set it in xcode as-
OR
By programmatically as-
let customButton = UIButton(type: .custom)
customButton.setTitle("this is Button", for: .normal)
customButton.setTitleColor(UIColor.blue, for: .normal)
customButton.frame = CGRect(x: 15, y: 50, width: 300, height: 500)
self.view.addSubview( customButton)
Now there is no more UIButton's blue background color
Changed UIButton type to Custom in IB worked for me.
Not a direct answer to OP's question but to remove this colour in a UIButton subclass you can do this:
override func layoutSubviews() {
super.layoutSubviews()
tintColor = .clear
}
What did it for me was changing the button.tintColor in the highlighted state. This is swift 3, iOS 10
override public var isHighlighted: Bool {
didSet {
self.tintColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
}
}
Or you can do the same in the interface builder
Choose button state
Choose button tint color
Swift Version
extension UIButton {
override public var highlighted: Bool {
didSet {
// clear background color when selected
self.layer.backgroundColor = .None
}
}
}
From iOS 15 onward, UIButton has property configuration. You can set clear color to property baseBackfroundColor to remove background color of UIButton in selected mode.
var config = UIButton.Configuration.plain()
config.baseBackgroundColor = .clear
button.configuration = config
Use...
[myButton setAdjustsImageWhenHighlighted:FALSE];
Not sure if this is the best way. But you could have an invisible button or view ontop of the actual button then recognize when the top button/view has been clicked.
Related
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
}
I have looked through other questions but can't find a definitive answer - I created my UIButton in my storyboard (not programmatically) and I am trying to tint the WHOLE button (not just text) on click. I have set my tint color to black and yet this does not affect the whole button.
I have tried setting my type to System as I heard that affects it but nothing has changed. Still no tint.
Furthermore I have to touch/click very "forcefully" (really press down if on device) to even trigger the tint color affecting the text on the button even though the button click registers.
The button's action func will be called so it does not affect functionality, but the text "highlighted state" seems to be only triggered if the user clicks really hard.
How can I tint the entire button? And why would the highlighted state only be triggered with really forced clicking?
Setting tint color -
Trying to implement with IBOutlet:
#IBOutlet var postBtn: UIButton!
postBtn = customButton()
postBtn.highlightedColor = UIColor.blueColor()
after creating custom class in new file:
public class customButton: UIButton {
public var highlightedColor = UIColor.blueColor()
public var unhighlightedColor = UIColor.clearColor()
override public var highlighted: Bool {
didSet {
if (highlighted) {
self.backgroundColor = UIColor.blueColor()
}
else {
self.backgroundColor = UIColor.clearColor()
}
}
}
}
I either get a bad access error if I declare postBtn initially as a customButton() or I am told postBtn has no member called highlightedColor. What am I doing wrong?
tint property sets the color of the button image and text.
As you don't have any image on your button, it only affect the color of the text
Also, tint will only affect the color of button's image when you set the button type to any except custom.
Now for example, we want to set the color of button image to red.
Then we will see:
In your case, you actually want to set the background color and title color of UIButton when button is highlighted.
For title color, you can directly use button.setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
For background color, there is no direct method you can use, but you can create a custom UIButton which override the highlighted property of UIButton or use setBackgroundImage:forState:
Custom UIButton
public class customButton: UIButton {
public var highlightedColor = UIColor.blueColor()
public var unhighlightedColor = UIColor.clearColor()
override public var highlighted: Bool {
didSet {
if (highlighted) {
self.backgroundColor = UIColor.blueColor()
}
else {
self.backgroundColor = UIColor.clearColor()
}
}
}
}
Usage:
let button1 = customButton()
let button2 = customButton()
button1.highlightedColor = UIColor.redColor()
button2.highlightedColor = UIColor.blueColor()
button1.unhighlightedColor = UIColor.clearColor()
button2.unhighlightedColor = UIColor.blackColor()
setBackgroundImage:forState:
Another method to achieve what you want is use setBackgroundImage:forState:. You may need to create an UIImage from UIColor first.
Generate a image from UIColor:
func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Usage:
button1.setBackgroundImage(getImageWithColor(UIColor.redColor(), size: button1.bounds.size), forState: .Highlighted)
button2.setBackgroundImage(getImageWithColor(UIColor.blueColor(), size: button2.bounds.size), forState: .Highlighted)
Try like this,
1) Set UIButton type to custom from storyboard
then write like below,
Create IBoutlet for that button like,
#IBOutlet var btnSubmit : UIButton!
Create click event of that button,
#IBAction func btnSubmitClick(sender : UIButton)
{
if(sender.selected == false)
{
self.btnSubmit.backgroundColor = UIColor.redColor()
self.btnSubmit.selected = true
}
else
{
self.btnSubmit.backgroundColor = UIColor.blueColor()
self.btnSubmit.selected = false
}
}
This will change your whole button background color. Hope this will help you :)
With regards your first question, you would need to do this in code. The tint only affects the text. If you wanted the background colour to change, you would need to change it manually as the button state changes. One way to do this would be to subclass UIButton and add a target/action on it for the relevant control events. In your case, you would listen to UIControlEventTouchDownto know when to change the background colour to your chosen 'highlight' colour, and UIControlEventTouchDragExitand UIControlEventTouchUpInside to know when to revert back to the normal state background colour.
Here's an existing implementation if you want to save time: https://github.com/TakeScoop/SwiftyButton
Swift 3
For anyone doing it programatically:
var button = UIButton(type: .system)
button.tintColor = UIColor.blue
I want to customize the cancel button inside the UISearchBar, that appears when the user type a text, to clear the text, see the image, I want to change the tint color of the button inside the red square NOT the button with "cancel" text
What I have tried :
[[UIButton appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor redColor]];
but it changes the color of the button with the text "cancel" not the icon to clear the text inside the textfield
it's not a duplicate question because I want to change the tint of the default clear image, NOT using a custom image, something like that :
How to change the tint color of the clear button on a UITextField
but for UISearchBar
UIImage *imgClear = [UIImage imageNamed:#"clear"];
[mySearchBar setImage:imgClear forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
Swift 4.2, 4.1+
It seems that the currentImage is nil for clearButton from Swift 4.1+. It might be working in the older versions.
So i created this class and the addition here is to provide your own image and color for clear button.
class SearchBar: UISearchBar {
var clearButtonImage: UIImage?
var clearButtonColor: UIColor = .white
override func layoutSubviews() {
super.layoutSubviews()
if let textField = self.value(forKey: "searchField") as? UITextField {
if let clearButton = textField.value(forKey: "clearButton") as? UIButton {
update(button: clearButton, image: self.clearButtonImage, color: clearButtonColor)
}
}
}
private func update(button: UIButton, image: UIImage?, color: UIColor) {
let image = (image ?? button.currentImage)?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.setImage(image, for: .highlighted)
button.tintColor = color
}
}
So now you can set the clearButton image as below to make it work,
let searchBar = SearchBar()
searchBar.clearButtonImage = UIImage(named: "clearIcon")
searchBar.clearButtonColor = .green
Storyboard or XIB
You have to set the SearchBar class as custom class for search bar shown below,
And outlet as below to set the images and colors etc
#IBOutlet private weak var searchBar: SearchBar!
How can I set the tint color of a MPVolumeView?
I see the method:
setMinimumTrackTintColor:
and the property
minimumTrackTintColor
however using either of those throws an exception.
I was told I need to call
setMinimumTintColor
or set the property
minimumTrackTintColor
on the underlying UISlider, however I don't know how to do that.
Thanks!
In iOS 7 you simply can change the slider color of a MPVolumeView like this:
CGRect rect1 = CGRectMake(17, 45, 220, 0);
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:rect1];
volumeView.tintColor = [UIColor colorWithRed:0.0f/255.0f green:255.0f/255.0f blue:127.0f/255.0f alpha:1.0f];
Hope this helps.
I have searched for answer to this for a very long time, because in my app I need to set volumeView colors dynamically. Since UISlider provides a way to change its tint color, you can cycle through MPVolumeView subviews until you find an instance of UISlider class and then operate on this one.
Here is the code in Swift:
func customSlider() {
let temp = mpVolView.subviews
for current in temp {
if current.isKind(of: UISlider.self) {
let tempSlider = current as! UISlider
tempSlider.minimumTrackTintColor = .yellow
tempSlider.maximumTrackTintColor = .blue
}
}
}
Result:
This worked for me to change the route button color too:
volumeView.tintColor = .green
if let routeButton = volumeView.subviews.compactMap({ $0 as? UIButton }).first,
let image = routeButton.image(for: .normal) {
routeButton.setImage(image.withRenderingMode(.alwaysTemplate), for: [])
}
I want to develop UINavigationBar and also set background color for that. I have created the UINavigationBar but I have problem with setting backgroundcolor. anyone please help me. Thanks.
[self.navigationController.navigationBar setBackgroundColor:[UIColor redColor]];
Try like this. I think it will be helpful to you.
Edit: updated the code to actually compile.
In the new iOs this it how it works:
self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
self.navigationController.navigationBar.barTintColor =[UIColor colorAzulNavegacion];
I have to look this up every time so adding my answer here (Swift). The code below is setting this for all navigation bars in the app. You could set each of these on individual navigation bars too if you wanted to.
You can set the translucency, title text color, background color (this is called barTintColor, thanks, Apple!), and bar button item foreground color, like so:
// Title text color Black => Text appears in white
UINavigationBar.appearance().barStyle = UIBarStyle.Black
// Translucency; false == opaque
UINavigationBar.appearance().translucent = false
// BACKGROUND color of nav bar
UINavigationBar.appearance().barTintColor = UIColor.redColor()
// Foreground color of bar button item text, e.g. "< Back", "Done", and so on.
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
You could use the tint property of the UINavigationBarto change it's color. Check this article about it. There is also UIAppearance, that allows you to change the background of every UINavigationBar of your application, which is quite powerfull in my opinion. You can check this.
You can set the tint color by using navbar.tintColor = [UIColor redColor];
See the reference here: apple docs
Try this:
navigationBar.tintColor = [UIColor blackColor];
self.navigationController?.navigationBar.translucent = false
self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
You can customize a UINavigationBar with the following propertys:
#property(nonatomic, assign) UIBarStyle barStyle
#property(nonatomic, retain) UIColor *tintColor
setBackgroundImage:forBarMetrics:
#property(nonatomic, copy) UIColor *backgroundColor
For more methods and propertys please check the class reference of UINavigationBar and UIView
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
Here it is in the context of doing something useful.
In this case programmatically creating/configuring a Navigation Bar item and item and
setting the background to black and the title to light gray.
Swift 5, iOS 15
#objc func addButtonPushed() {
print("Add button!")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let rightButton = UIBarButtonItem(image: UIImage(systemName: "plus"), style: .plain,
target:self, action: #selector(addButtonPushed))
let standaloneItem = UINavigationItem()
standaloneItem.title = "Herding Cats"
standaloneItem.rightBarButtonItem = rightButton
navBar.items = [standaloneItem]
navBar.delegate = self
navBar.barStyle = UIBarStyle.default
navBar.isTranslucent = true
navBar.barTintColor = .black
navBar.titleTextAttributes = [.foregroundColor: UIColor.lightGray]
.
.
.
}