ios 如何在 Swift 中为State设置 UIButton 背景颜色:UIControlState.Highlighted
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26600980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set UIButton background color forState: UIControlState.Highlighted in Swift
提问by David Wood
I can set the background color for a button but I can't work out how to set the background color for UIControlState.Highlighted
. Is it even possible? or do I need to go down the setBackgroundImage
path?
我可以为按钮设置背景颜色,但我不知道如何设置 UIControlState.Highlighted
. 甚至有可能吗?还是我需要走这setBackgroundImage
条路?
回答by winterized
If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:
如果有人停下来,如果你不止一次需要它,那么另一种方式可能更容易......我为 UIButton 编写了一个简短的扩展,它工作得很好:
for Swift 3
对于 Swift 3
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, forState: forState)
}
}
for Swift 4
对于 Swift 4
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControl.State) {
self.clipsToBounds = true // add this to maintain corner radius
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
}
You use it just like setBackgroundImage
:
你使用它就像setBackgroundImage
:
yourButton.setBackgroundColor(color: UIColor.white, forState: UIControl.State.highlighted)
回答by Maverick
Syntax changes to @winterized extensionfor Swift 3+ syntax
语法变为@winterized扩展为雨燕3+语法
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}}
回答by Steve Rosenberg
Below will be one way to go. Two IBActions. One to control background color when depressing a button, one on release.
下面将是一种方法。两个 IBAction。按下按钮时控制背景颜色,释放时控制背景颜色。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
button.backgroundColor = UIColor.whiteColor()
}
@IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
button.backgroundColor = UIColor.blueColor()
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
When you look at the autocomplete options for your button after adding a period, you can set a background color, but not for specified state. You can only set background images. Now of course if you are married to doing it this way instead of using the method I show above, you could load an image of the desired color as the background image using the setbackgroundImageForState property.
添加句点后查看按钮的自动完成选项时,您可以设置背景颜色,但不能设置指定状态。您只能设置背景图像。现在,当然,如果您愿意这样做而不是使用我上面展示的方法,您可以使用 setbackgroundImageForState 属性加载所需颜色的图像作为背景图像。
回答by kaktusgruen
Swift 4 Version of this solution:
此解决方案的Swift 4 版本:
extension UIButton {
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
setBackgroundImage(colorImage, for: state)
}
}
回答by Mete
Seems nobody here has mentioned using Key Value Observationyet, but it's another approach.
似乎这里还没有人提到使用Key Value Observation,但这是另一种方法。
A reason for doing so instead of picking the other answers here is you don't need to go creating new images all the time nor be concerned with secondary effects of assigning images to buttons (e.g. cornerRadius effects).
这样做而不是在这里选择其他答案的一个原因是您不需要一直创建新图像,也不需要关心将图像分配给按钮的次要效果(例如,cornerRadius 效果)。
But you'll need to create a class for the observer, who would be responsible for storing the different background colours and applying them in the observeValue()
method.
但是您需要为观察者创建一个类,他将负责存储不同的背景颜色并在observeValue()
方法中应用它们。
public class ButtonHighlighterObserver: NSObject {
var observedButton:UIButton? = nil
var backgroundColor: UIColor = UIColor.white
var backgroundHighlightColor: UIColor = UIColor.gray
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// Perform background color changes when highlight state change is observed
if keyPath == "highlighted", object as? UIButton === observedButton {
observedButton!.backgroundColor = observedButton!.isHighlighted ? self.backgroundHighlightColor : self.backgroundColor
}
}
}
}
Then all you need to do is manage addObserver / removeObserver during operation:
然后你需要做的就是在操作过程中管理 addObserver / removeObserver :
// Add observer to button's highlighted value
button.addObserver(anObserver, forKeyPath: "highlighted", options: [.new], context: nil)
anObserver.observedButton = button
// ...
// And at deinit time, be sure you remove the observer again
anObserver.observedButton?.removeObserver(item, forKeyPath: "highlighted")
anObserver.observedButton = nil
回答by Puji Wahono
Update Swift 4
更新 Swift 4
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
Event Button Action
事件按钮操作
Show Touch On Hightlight
在突出显示上显示触摸
回答by Maximelc
Swift 4+ compatibility for the accepted answer :
已接受答案的 Swift 4+ 兼容性:
extension UIButton {
/// Sets the background color to use for the specified button state.
func setBackgroundColor(color: UIColor, forState: UIControlState) {
let minimumSize: CGSize = CGSize(width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(minimumSize)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(origin: .zero, size: minimumSize))
}
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.clipsToBounds = true
self.setBackgroundImage(colorImage, for: forState)
}
}
Compatible SwiftLint and fix the bug of broken auto layout / corner radius.
兼容 SwiftLint 并修复自动布局/圆角半径损坏的错误。
回答by poGUIst
Why not?
为什么不?
@implementation UIButton (Color)
- (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
{
[self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
}
@end
回答by Sonika Sood
Can we do the same using run time attributes?
我们可以使用运行时属性来做同样的事情吗?
@IBInspectable var HighlightedBackground: Bool {
get {
return true
}
set {
layer.backgroundColor = Common.sharedInstance.OrangeColor.CGColor
print("highlighted state")
}
}