我查看了其他问题,但找不到明确的答案 - 我在我的 Storyboard中创建了我的 UIButton(不是以编程方式),我试图在点击时为整个按钮(不仅仅是文本)着色。我已将色调颜色设置为黑色,但这不会影响整个按钮。
我曾尝试将我的类型设置为系统,因为我听说这会影响它,但没有任何改变。仍然没有色调。
此外,我必须非常“用力”地触摸/单击(如果在设备上确实按下)以触发影响按钮上文本的色调,即使按钮单击注册也是如此。
按钮的 Action 函数将被调用,因此它不会影响功能,但文本“突出显示状态”似乎只有在用户用力点击时才会触发。
如何为整个按钮着色?为什么只有在真正用力点击时才会触发突出显示状态?
设置色调颜色 -
尝试使用 IBOutlet 实现:
@IBOutlet var postBtn: UIButton!
postBtn = customButton()
postBtn.highlightedColor = UIColor.blueColor()
在新文件中创建自定义类后:
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()
}
}
}
}
如果我最初将 postBtn 声明为 customButton()
,或者我被告知 postBtn 没有名为 highlightedColor 的成员,我会得到错误的访问错误。我做错了什么?
最佳答案
tint
property sets the color of the button image and text.
因为你的按钮上没有任何图像,它只会影响文本的颜色
此外,tint
只会在您将按钮类型设置为除custom
之外的任何类型时影响按钮图像的颜色。
现在例如,我们要将按钮图像的颜色设置为红色。
然后我们会看到:
在您的例子中,您实际上想要在突出显示按钮时设置 UIButton 的背景颜色和标题颜色。
标题颜色可以直接使用button.setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
对于背景颜色,没有直接的方法可以使用,但是您可以创建一个自定义的 UIButton 来覆盖 UIButton 的 highlighted
属性或使用 setBackgroundImage:forState:
自定义 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()
}
}
}
}
用法:
let button1 = customButton()
let button2 = customButton()
button1.highlightedColor = UIColor.redColor()
button2.highlightedColor = UIColor.blueColor()
button1.unhighlightedColor = UIColor.clearColor()
button2.unhighlightedColor = UIColor.blackColor()
setBackgroundImage:forState:
另一种实现您想要的方法是使用 setBackgroundImage:forState:
。您可能需要先从 UIColor
创建一个 UIImage
。
从 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
}
用法:
button1.setBackgroundImage(getImageWithColor(UIColor.redColor(), size: button1.bounds.size), forState: .Highlighted)
button2.setBackgroundImage(getImageWithColor(UIColor.blueColor(), size: button2.bounds.size), forState: .Highlighted)
关于ios - UIButton 色调颜色不适用于整个按钮?设置在 Storyboard中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716493/