gpt4 book ai didi

swift - @IBDesignable View 上的标签颜色在​​不同设备上显示不同

转载 作者:行者123 更新时间:2023-11-30 11:24:21 26 4
gpt4 key购买 nike

我有一个 @IBDesignable 自定义 View 。它包含一个带有两个子类 UILabels 的 UIView。 UILabel 的自定义子类正在设置它的字体。

我想要实现的目标是通过将 View 的背景颜色设置为可检查的属性,使文本颜色适当更改以使其清晰易读。

我的代码如下。 Custom.Colour.<name>只是定义颜色的枚举。

@IBDesignable
class CustomMiniView: UIView, NibLoadable {

public var view:UIView!

@IBOutlet weak var colourView: UIView!
@IBOutlet weak var headingLabel: CustomUILabel!
@IBOutlet weak var amountLabel: CustomUILabel!

@IBInspectable var blockColor:UIColor! {
didSet {

self.colourView.backgroundColor = blockColor

switch blockColor {

case Custom.Colour.darkBlue:
headingLabel.textColor = .white
amountLabel.textColor = .white

case Custom.Colour.blue:
headingLabel.textColor = .white
amountLabel.textColor = .white

case Custom.Colour.lightBlue:
headingLabel.textColor = Custom.Colour.grey
amountLabel.textColor = Custom.Colour.blue

case Custom.Colour.green:
headingLabel.textColor = .white
amountLabel.textColor = .white

case Custom.Colour.lightGreen:
headingLabel.textColor = Custom.Colour.grey
amountLabel.textColor = Custom.Colour.blue

case Custom.Colour.yellow:
headingLabel.textColor = Custom.Colour.grey
amountLabel.textColor = Custom.Colour.grey

default : printError("We have not handled text colours for a background of this colour. = \(blockColor.hexString)")
}
}
}

public override init(frame: CGRect) {
super.init(frame: frame)

self.setupFromNib()
self.commonInit()
}

public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

self.setupFromNib()
self.commonInit()

}

func commonInit() {
self.backgroundColor = .clear
}

}

这对我来说效果很好,但是随后我收到报告称文本到处都显示为白色,并收到了一张屏幕截图,这让我很困惑。当我在模拟器和不同的设备中运行它时,我发现它不起作用。以下是我的 iPad 上发生的情况和我期望发生的情况的两个屏幕截图,以及其他一些设备和模拟器上发生的情况的屏幕截图。

这就是我的设备上发生的情况和预期结果。 Correct and expected result.

这就是其他设备上发生的情况,并且结果不正确。 enter image description here

这在不同的设备上会出现不同的原因吗?我不知道原因或如何解决这个问题。

最佳答案

感谢上面的评论,我找到了解决办法。

我没有对颜色进行切换,而是对有效颜色的 .hexString 进行了切换。

    switch blockColor.hexString {

case Custom.Colour.darkBlue.hexString :

根据记录,hexString 是 UIColor 的扩展

    var hexString: String {
let colorRef = cgColor.components
let r = colorRef?[0] ?? 0
let g = colorRef?[1] ?? 0
let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
let a = cgColor.alpha

var color = String(
format: "#%02lX%02lX%02lX",
lroundf(Float(r * 255)),
lroundf(Float(g * 255)),
lroundf(Float(b * 255))
)

if a < 1 {
color += String(format: "%02lX", lroundf(Float(a)))
}

return color
}

我仍然不确定为什么打开 hexString 有效,而枚举中的 UIColor 不能一致工作,但感谢相关评论帮助我找到了自己修复它的解决方案。另一个问题是为什么打开 UIColor 会不可靠,但现在又恢复工作了。

关于swift - @IBDesignable View 上的标签颜色在​​不同设备上显示不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50925875/

26 4 0