There are different ways of setting up backgrounds in Swift, depending on the object, method, background type etc.
We will go through some of these here.
Setting up a background image for a UIView:
1 |
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "myImage.png")) |
Replace “myImage.png” with the name of your image.
Note: Make sure you add your images to the Bundle first.
To do that – right click anywhere in the bundle files in the Project Navigator and
select ‘Add Files to “project_name”‘, you can also drag the images there from Finder:
Make sure you have the ‘Copy the items if needed’ option checked.
To simply set the color of a UIView you would use this:
1 |
view.backgroundColor = UIColor.yellowColor() |
1 |
view2.backgroundColor = UIColor.blackColor() |
replace view or view2 with the name of your UIView and the color of your choice.
Once you type UIColor. you should get a list of the available UIColors.
Just in case here are the ones provided by Apple as a UIColor:
- blackColor
- darkGrayColor
- lightGrayColor
- whiteColor
- grayColor
- redColor
- greenColor
- blueColor
- cyanColor
- yellowColor
- magentaColor
- orangeColor
- purpleColor
- brownColor
- clearColor
In case you want to use RGB colors you can use a function like this:
1 2 3 4 5 6 7 8 9 10 11 |
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)) } // rbgValue - define hex color value // alpha - define transparency value // returns - CGColor |
You would use the function like this:
1 |
view.backgroundColor = UIColorFromHex(0x9933FF, alpha: 0.9) |
Another way of doing it would be like this:
1 |
view.backgroundColor = UIColor(red: 0.3, green: 0.5, blue: 0.7, alpha: 1.0) |