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
}
Related
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...")
}
I'd like to put a background color for just the title of TabBar using swift I tried to use NSAttributedString.Key.backgroundColor but it not appears color in the background.
Can anybody help me to change the background color for just the title of TabBar?
I need to add yellow color to the background to title in the normal state not selected.
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.gray], for: .selected)
This works for a single item. If you'd like to change the color for all items in the tab bar, try parsing through them like such
for item in self.tabBar.items! {
item.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)
item.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.gray], for: .selected)
}
you can add the following code snippet to your viewDidLoad:
UITabBar.appearance().barTintColor = UIColor.black // your color
In short, how can I change the color of the black button items (while maintaining control over their size)?
Longer version: I am programmatically adding a number of custom UIBarButtonItems to a UIToolbar. I'm using the solution found here so that I can control the size of the items.
While this fixes the UIBarButtonItem size issue, it does not respect tintColor like a typical UIBarButtonItem would. So I get something like this:
The large white item is the color I want, but not the size. This item was simply added in IB with the tintColor set to default.
The small black items are the size I want, and were added with the following code (N.B. the lines marked with // Not producing intented result):
for e in (self.profile?.expressions)! {
let button = UIButton()
button.setImage(UIImage(named: "emojiph"), for: .normal)
button.addTarget(self, action: #selector(onEmojiInsert), for: .touchUpInside)
let barItem = UIBarButtonItem(customView: button)
barItem.tag = e.family_expression_id
let wConstraint = barItem.customView?.widthAnchor.constraint(equalToConstant: 32)
wConstraint?.isActive = true
let hConstraint = barItem.customView?.heightAnchor.constraint(equalToConstant: 32)
hConstraint?.isActive = true
// Not producing intented result
button.tintColor = UIColor.white
// Not producing intented result
barItem.customView?.tintColor = UIColor.white
// Not producing intented result
barItem.tintColor = UIColor.white
self.emojibar.items?.append(barItem)
// Add flexible spacers
if (e.family_expression_id < (self.profile?.expressions.count)!) {
self.emojibar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil))
}
}
A workaround would be to provide the white image assets, but I'd prefer to find a more elegant solution if it exists.
To make the button change the color of the presented image to match the tint color then you need to initiate the button as a system type
let button = UIButton(type: .system)
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)
I know how to change the background color but what about the actual text? There doesn't seem to be a member on a UIButton called "color" or anything like that.
My code:
#IBAction func yellowBtnClicked(sender: UIButton) {
gameboard.image = UIImage(named: "Yellow_gb")
resultsView.image = UIImage(named: "Yellow_results")
colorsView.image = UIImage(named: "Yellow_colors")
colorsBtn.color = UIColor.brownColor() //This line has the issue
}
There is no property setter color in UIButton. use instead setTitleColor.Write this in viewWillAppear
colorsBtn.setTitleColor(UIColor.brownColor(), forState: UIControlState.Normal)
This will change title color to brown for UIControlState.Normal
To set the color of title when button is in Highlighted state use
colorsBtn.setTitleColor(UIColor.brownColor(), forState: UIControlState.Highlighted)
Swift 3.0 example:
colorsBtn.setTitleColor(UIColor .white, for: UIControlState.normal)
colorsBtn.setTitleColor(UIColor .black, for: UIControlState.highlighted)