ios - 无法将颜色设置为分段控制
问题描述
我有这样的颜色“CC0000”
现在要将此颜色分配给我选择的段,我首先尝试使用此扩展。
extension UIColor {
// MARK: - Initialization
convenience init?(hex: String) {
var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
var rgb: UInt32 = 0
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 1.0
let length = hexSanitized.count
guard Scanner(string: hexSanitized).scanHexInt32(&rgb) else { return nil }
if length == 6 {
r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
b = CGFloat(rgb & 0x0000FF) / 255.0
} else if length == 8 {
r = CGFloat((rgb & 0xFF000000) >> 24) / 255.0
g = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0
b = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0
a = CGFloat(rgb & 0x000000FF) / 255.0
} else {
return nil
}
self.init(red: r, green: g, blue: b, alpha: a)
}
// MARK: - Computed Properties
var toHex: String? {
return toHex()
}
// MARK: - From UIColor to String
func toHex(alpha: Bool = false) -> String? {
guard let components = cgColor.components, components.count >= 3 else {
return nil
}
let r = Float(components[0])
let g = Float(components[1])
let b = Float(components[2])
var a = Float(1.0)
if components.count >= 4 {
a = Float(components[3])
}
if alpha {
return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
} else {
return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
}
}
}
我就这样使用它..
let color = UIColor(hex: selectedColor)
. //“selectedColor”是“CC0000”
但是现在当我打印时color
,我得到Optional(UIExtendedSRGBColorSpace 0.8 0 0 1)
但我不确定如何将这种颜色设置tintColor
为我的 segmentControl 的颜色。如果我做类似的事情self.segCriticalityABCD.tintColor = color
,它不会显示任何颜色..
解决方案
您的扩展程序创建的颜色工作正常:
guard let color = UIColor(hex: "#CC0000") else { return }
这将设置所选段的文本颜色:
segmentedControl.setTitleTextAttributes([.foregroundColor: color], for: .selected)
这将设置您选择的段的颜色:
segmentedControl.selectedSegmentTintColor = color
其他有价值的信息可在此处获得:
如何为单个段设置 UISegmentedControl Tint Color
和这里:
https://developer.apple.com/documentation/uikit/uisegmentedcontrol
推荐阅读
- selenium - 如何使用 Selenium Webdriver Python 跳过身份验证弹出窗口
- python - Geopandas - ValueError:无法转换幼稚的几何图形。请先在对象上设置 crs
- java - 推荐用于表类数据和随机(索引)读取访问的 Java(或 Kotlin)序列化格式?
- typescript - 用于前端和后端的打字稿导入/导出
- reactjs - 在 react native 中创建日历组件
- javascript - 在页面中搜索特定 URL 并将第一个实例复制到剪贴板
- swiftui - 取消订阅组合框架
- multithreading - 多线程多核 cpu 渲染图像是否比单线程多核 cpu 更快?
- android-studio - 如何更改 *.arb 文件中本地化文本的字体
- go - Heroku Go 应用程序崩溃,找不到版本“GLIBC_2.32”,bin/main 需要