不久前,我找到了一些代码,用于根据状态更改 UIButton 的背景颜色。代码如下所示:
extension UIButton {
func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
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)
}
}
现在我想知道如何正确测试此功能。有什么想法吗?
谢谢
最佳答案
- 调用你的扩展方法
- 调用
.backgroundImage(for:)
获取UIImage - 将 UIImage 渲染为像素
- 比较像素颜色值
关于swift - 断言从 UIGraphics 生成的 UIImage 全是红色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57063390/