UIView background color in Swift - swift

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];, but that does not work the same way in Swift. I have looked around and because Swift is only about a week old, I cannot find an answer.
Does anyone have any suggestions?

self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red

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.

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+

You can use the line below which goes into a closure (viewDidLoad, didLayOutSubViews, etc):
self.view.backgroundColor = .redColor()
EDIT Swift 3:
view.backgroundColor = .red

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)
}
}

In Swift 4, just as simple as Swift 3:
self.view.backgroundColor = UIColor.brown

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

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

In the Xcode 13, the shortcut ColorLiteral does not work anymore.
Now, you have to use this shortcut: #colorLiteral(

Related

iOS 13 system color for UIButton

Apple recommends using system colors to adapt apps to light and dark mode automatically, for example:
myLabel.textColor = UIColor.secondaryLabel
Here Apple lists various properties to be used, such as the one in the example above, and system colors for background, placeholder text, and more.
But it doesn't list a property for UIButton elements.
Which property or other method should we use to adapt UIButtons to theme changes?
As of now, I'm doing this:
myButton.tintColor = UIColor.link
which is supposedly for links but is the only "clickable" property I found.
I'm not looking to use something like UIColor.systemRed, rather something like UIColor.systemBackground, which adapts automatically to the current theme.
I hope you create colored Assets not one by one. You can use this function to tint images as a extension of UIImageView. I also use the same technique for buttons.
func setImageAndColor(image: UIImage, color: UIColor) {
let templateImage = image.withRenderingMode(.alwaysTemplate)
self.image = templateImage
self.tintColor = color
}
In case you want to define all you own colors, I suggest to create a singleton class named Colors:
import UIKit
class Colors {
static let shared = Colors()
var statusBarStyle: UIStatusBarStyle = .lightContent
private init(){}
func setLightColors() {
statusBarStyle = .darkContent
yourColor = UIColor( // choose your favorite color
styleColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)//white
labelColor = UIColor(red: 15/255, green: 15/255, blue: 15/255, alpha: 1)
subLabelColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 1)
............ set values for all colors from here.
}
func setDarkColors() {
statusBarStyle = .lightContent
yourColor = // choose your favorite color
............
}
// set initial colors
var yourColor: UIColor =
}
If somebody is interested in the whole Colors class, text me or comment below.
I access the colors singleton by:
Colors.shared.yourColor
Also for first configuration I set in the very first VC the darkmode number (0-Auto; 1-On; 2-Off):
if darkmodeNumber == 0 {
if traitCollection.userInterfaceStyle == .light {
print("Light mode")
Colors.shared.setLightColors()
} else {
print("Dark mode")
Colors.shared.setDarkColors()
}
} else if darkmodeNumber == 1 {
Colors.shared.setDarkColors()
} else if modeNumber == 2 {
Colors.shared.setLightColors()
}
}
The statusbar should then change also the right way.
Use any system colors you like. They are all adaptive. I applied the system gray color to a button's text:
The color changes when we switch between light and dark mode.

Change colour of textView placeholder

I am using a material design library for ios but i didn't found any property on how to change it's placeholder colour when there is no data entered. I have to use a standard background and the placeholder is not visible if it's gray
You can use an attributed string for this:
let attrString = NSAttributedString(string: "Text", attributes: [NSForegroundColorAttributeName:UIColor.blueColor()])
myTextField.attributedPlaceholder = attrString
Version 1.34.5 allows the textField placeholder text color to be set like so:
textField.placeholderTextColor = MaterialColor.grey.base
Use ATKit.
Refer: https://aurvan.github.io/atkit-ios-release/index.html
ATTextView Class: https://aurvan.github.io/atkit-ios-release/helpbook/Classes/ATTextView.html
Code:
import ATKit
#IBOutlet weak var messageTextView :ATTextView!
self.messageTextView.placeholderColor = UIColor(red: 173.0/255.0, green: 216.0/255.0, blue: 230.0/255.0, alpha: 1.0)
Screenshot:
https://github.com/CosmicMind/Material/issues/169
See issue 169 on this. Release 1.34.0 includes this ability.
EDIT
New code in Material library is
textField.placeholderTextColor = MaterialColor.green.base

Changing Tab Bar Color (Swift)

I am trying to change the tab bar color in a view controller in XCode using swift. I have a hex that I matched up to an RGB value and I am trying to set that in this code. (Which does not work)
let color = UIColor(red: 41, green: 40, blue: 39, alpha: 1.0)
UITabBar.appearance().barTintColor = color
However this code does:
UITabBar.appearance().barTintColor = UIColor.whiteColor()
Can anyone explain why this doesn't work, and what I can do to fix it?
To use RGB values, just divide them by 255.0. This will produce a float value between 0 and 1.
let color = UIColor(red: 41.0/255.0, green: 40.0/255.0, blue: 39.0/255.0, alpha: 1.0)
It doesn't work because all of your RGB components are greater than 1, which is the maximum available value per-channel. You're probably thinking of the color channels as bytes, but that wouldn't scale to varying color bit depths. (For example, it was common to render to RGB565, not RGBA8888 in early versions of iOS. And you can probably expect Apple to make screens with 16-bit accuracy the norm, in the near future.) Floats from 0 to 1 are employed, to divorce the bit depth from the color representation.
https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIColor_Class/index.html#//apple_ref/occ/instm/UIColor/initWithRed:green:blue:alpha:
iOS 10 Swift 3.0
If you don't mind to use swift frameworks then us UINeraida to change Tabbar background as UIColor or HexColor or UIImage and change complete forground color.
For UITabBar
neraida.tabbar.background.color.uiColor(UIColor.orange, isTranslucent: false, viewController: self)
//change tab bar tint color //(select,unselect)
neraida.tabbar.foreground.color.uiColor((UIColor.white,UIColor.green), viewController: self)
//set Background Image for tab bar
neraida.tabbar.background.image("background", isTranslucent: false, viewController: self)
This way worked for me:
tabBarController?.tabBar.backgroundColor = .red

Serious SpriteKit UIColor bug on iPhone 5S

I've found a serious swift-bug in SpriteKit while working with SKSpriteNodes and their colors.
This code works fine on all iPhones beside the iPhone 5S:
var color1 = UIColor(red: 123/255, green: 123/255, blue: 123/255, alpha: 1)
var color2 = UIColor(red: 123/255, green: 123/255, blue: 123/255, alpha: 1)
var sprite = SKSpriteNode(color: color1, size: CGSizeMake(100, 100))
if(sprite.color == color2){
println("Same color")
}
As you see, the two colors are the absolut same. But on the iPhone 5S simulator, the if isn't called.
Has somebody else the same problem and can provide a solution?
According to the documentation here:
Sprite Kit works only with solid colors. For best results, use the
preset colors provided by the platform class or a custom color defined
in the RGBA device color space.
As a result somehow the SKSpriteNode has made some changes to the color parameter in the init function. You can see it if you call encode:
sprite.color.encode() // 140,646,370,382,768
color1.encode() // 140,646,367,110,928
If you use predefined color values, then your problem goes away:
var color3 = UIColor.blueColor()
var sprite3 = SKSpriteNode(color: color3, size: CGSizeMake(100, 100))
sprite3.color == color3 // true
You are comparing pointer values, not the actual color. Seeing that these are UIColor instances, you have to compare them using isEqual (showing ObjC code as I don't know what it looks like in Swift - or perhaps Swift is in fact using isEqual behind the scenes):
if ([sprite.color isEqual:color2])
If implemented correctly by UIColor this will compare the actual color values rather than the pointers.

How do you use the appropriate color class for the current platform?

I'm trying to share my Scene Kit code across iOS and OS X, but the API calls that accept colors (and images) take either UIColor/UIImage or NSColor/NSImage depending on the platform. How do I create the right class in Swift without duplicating the code?
Use conditional compilation and type aliases:
#if os(OSX)
typealias Color = NSColor
typealias Image = NSImage
#else
typealias Color = UIColor
typealias Image = UIImage
#endif
Then use Color instead of UIColor or NSColor:
self.gameView!.backgroundColor = Color(red: 0, green: 0.2, blue: 0.5, alpha: 1)
Edit 2016-01-17: As DDPWNAGE noted above, Apple has created SKColor with basically the same definition.