ios - 如何为 UIButton 设置自定义背景颜色?

标签 ios swift uibutton uicolor

我想知道用于更改按钮背景颜色的不同类型的代码。在我的项目中,我使用:

button4.backgroundColor = UIColor.green

但它只给我有限数量的颜色选项,因为它是 UIColor。我想知道我是否可以编写一段不同的代码来更灵活地设置按钮的颜色。

感谢您提供的任何帮助。

最佳答案

But it only gives me a restricted amount of colour options since it is UIColor.

在使用预定义的静态颜色时,这是正确的。但是,毫无疑问,您可以获得另一种颜色,这不是预定义的颜色。

例如,假设您有一个要在您的应用中使用的自定义 rgb 颜色(按钮背景颜色),如:red: 100 green: 44 blue: 63,您可以得到它通过使用:

init(red:green:blue:alpha:)

Initializes and returns a color object using the specified opacity and RGB component values.

如下:

let myCustomRGBColor = UIColor(red: 100.0/255.0, green: 44.0/255.0, blue: 63.0/255.0, alpha: 1.0)

请注意,值在 255.0 上进行划分,因为 UIColor 的 rgb 值介于 0 和 1 之间。

另外,请注意 UIColor还有很多其他initializers用于创建自定义颜色对象。

关于ios - 如何为 UIButton 设置自定义背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349642/

相关文章:

ios - 显示 searchResultsController 时出现 UISearchBar AutoLayout 错误

ios - 如何创建几乎与我的 GameScene 接壤的坐标?

swift - 使用 NSTimer is Swift 导致 'deinit' 不调用

ios - 为什么要执行我的 segue?

iphone - UIButton Action 不使用 UITapGestureRecognizer iPhone 应用程序调用?

ios - 带有背景图像的 UIButton 突出显示状态错误

ios - 从 Images.xcassets 加载图像

ios - (null) 无法在 Xcode 6.3.1 中运行 armv7f

swift - 为什么这个 View 在 awakeFromNib() 中是 nil?

ios - 将按钮数组添加到特定 subview