UIView background color in Swift

后端 未结 8 968
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:38

    Try This, It worked like a charm! for me,

    The simplest way to add backgroundColor programmatically by using ColorLiteral.

    You need to add the property ColorLiteral, Xcode will prompt you with a whole list of colors in which you can choose any color. The advantage of doing this is we use lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard.

    Follow steps ,

    1) Add below line of code in viewDidLoad() ,

    self.view.backgroundColor = ColorLiteral
    

    and clicked on enter button .

    2) Display square box next to =

    3) When Clicked on Square Box Xcode will prompt you with a whole list of colors which you can choose any colors also you can set HEX values or RGB

    4) You can successfully set the colors .

    Hope this will help some one to set backgroundColor in different ways.

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

    I see that this question is solved, but, I want to add some information than can help someone.

    if you want use hex to set background color, I found this function and work:

    func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
        let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
        let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
        let blue = CGFloat(rgbValue & 0xFF)/256.0
    
        return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
    }
    

    I use this function as follows:

    view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
    

    some times you must use self:

    self.view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)
    

    Well that was it, I hope it helps someone .

    sorry for my bad english.

    this work on iOS 7.1+

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