swift - 按下 UIButton 时如何更改它的颜色?
问题描述
我想知道如何在按下 UIButton 时更改它的颜色。默认情况下,当您按下 UIButton 时,它会变成淡蓝色。当我按下它时,如何将它从褪色变为紫色。我如何在 Swift 4 中做到这一点?我可以更改某种属性吗?
解决方案
斯威夫特 4.2
将此扩展用于按钮:
extension UIButton {
func setBackgroundColor(_ color: UIColor, forState controlState: UIControl.State) {
let colorImage = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in
color.setFill()
UIBezierPath(rect: CGRect(x: 0, y: 0, width: 1, height: 1)).fill()
}
setBackgroundImage(colorImage, for: controlState)
}
}
简单的用法:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton()
button.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
button.setBackgroundColor(.red, forState: .normal)
button.setBackgroundColor(.blue, forState: .highlighted)
view.addSubview(button)
}
希望这能让你微笑:)
推荐阅读
- swift - Metal中两个数组的Int64元素的比较
- php - 即使“AllowNoPassword”设置为 true,PhpMyAdmin 仍会显示登录页面
- java - 在java中计算字符串中的元音不计算第一个字符串
- linux - sed 替换字符串
- javascript - 无法在 Vue 中访问函数之外的 Firebase 数据库数据
- c - 如何在 C 中的函数中拆分字符串?
- python - 插入到外键引用的两个表中 - flask_sqlalchemy
- jenkins - Jenkins在执行shell命令时找不到目录
- c# - 在 C# 中创建 AI 以完成一个简单的游戏
- r - 我如何在 tidyverse 中使用 purr 递归地在 tibble 中添加值