33
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift4】UIColorをRGB(0~255)で指定したい

Last updated at Posted at 2018-02-26

SwiftのUIcolorのRGB値は、256段階ではなく、0~1.0までの値で指定するようになっています。
https://developer.apple.com/documentation/uikit/uicolor

まあこれが指定しにくい...

そんなときは、UIcolorのextentionを作るか、UIcolorのRGB値の引数に255で割った値を直接渡しちゃいましょう!

extentionを作る

extension UIColor {
    class func rgba(red: Int, green: Int, blue: Int, alpha: CGFloat) -> UIColor{
        return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
    }
}

//使い方
let button = UIButton()
button.backgroundColor = UIColor.rgba(red: 117, green: 194, blue: 57, alpha: 1)

RGB値を直接渡す

こっちが手っ取り早い。

let button = UIButton()
button.backgroundColor = UIColor(red: 117/255, green: 194/255, blue: 57/255, alpha: 1)
33
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?