UIView background color in Swift

后端 未结 8 967
Happy的楠姐
Happy的楠姐 2020-12-25 09:51

Is there a way to set the UIView background color with Swift?

I know that in Objective-C, you would use self.view.backgroundColor = [UIColor redColor];,

相关标签:
8条回答
  • 2020-12-25 10:17
    self.view.backgroundColor = UIColor.redColor()
    

    In Swift 3:

    self.view.backgroundColor = UIColor.red
    
    0 讨论(0)
  • 2020-12-25 10:25

    You can use this extension as an alternative if you're dealing with RGB value.

    extension UIColor {
        static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
            return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
          }
        }
    
    0 讨论(0)
  • 2020-12-25 10:27

    You can use the line below which goes into a closure (viewDidLoad, didLayOutSubViews, etc):

    self.view.backgroundColor = .redColor()
    

    EDIT Swift 3:

    view.backgroundColor = .red
    
    0 讨论(0)
  • 2020-12-25 10:27

    In Swift 4, just as simple as Swift 3:

    self.view.backgroundColor = UIColor.brown
    
    0 讨论(0)
  • 2020-12-25 10:31

    If you want to set your custom RGB color try this:

    self.view.backgroundColor = UIColor(red: 20/255.0, green: 106/255.0, blue: 93/255.0, alpha: 1)

    Don't forget to keep /255.0 for every color

    0 讨论(0)
  • 2020-12-25 10:33

    The response by @Miknash and @wolfgang gutierrez barrera was helpful to me. Only difference was I had to add rgbValue: to the function call.

    UIColorFromHex(rgbValue: 0xA6D632,alpha: 1 ) like so

    0 讨论(0)
提交回复
热议问题