How To Set Background Color In Swift?

Adding background colors to specific views or to an entire app is a common thing you’ll need to do as an iOS developer.

Find the view or view controller you want to change the background color of.

Open it up in the interface builder and open the Attributes Inspector. Find the background color field and set it to the color you want.

You can also do it purely in code, use the interface builder or even set specific elements such as a button to have a certain background color. I’ll go over the rest of the details in this article.

Setting background colors in iOS with pictures

First, open up the view that you want the background color to change on in the interface builder. Select the view and select the Attributes Inspector

make_12

Once you’ve found the background field, click on that drop down menu and you’ll have some options for colors. When you click custom color, you’ll get a color wheel and some other color options.

make_13

If you have a specific color from your design specifications or from your color scheme, you can use the second tab to type it in.

make_14

Most designers or specifications will have the color listed a HEX value. Be sure to select RBG Sliders from the dropdown so you can type in the HEX color value.

You can follow similar steps to make other UI elements have background colors.

This is how the Attributes Inspector looks like for buttons:

make_15

It also works for labels, views and most other elements you’ll find in the UI library.

Save colors to increase productivity in Xcode

For most applications, you’ll usually have a color scheme or color list. These are the set of colors your app uses the most. They typically include colors for the background, primary action, secondary action, and text color. Some color schemes also have a color for emphasis or highlighted elements.

You could just paste in the HEX value every time you needed one of these colors. Xcode has a feature that will enable to save your color schemes and ultimately save you some time while building apps.

To save a set of colors open up the Colors dialog by selecting custom color when you click the background drop-down menu. In this color dialog, select the third tab that says Color Palettes when you hover over it. Hit the little gear icon next to the drop-down menu.

make_16

Select new, which will create a new color palette for you. You can name it whatever, I choose to name mine Main Colors. Choose your colors either using the wheel in the first tab or the sliders in the second tab. When you’ve got the color you want to save, hit the plus (+) icon and it will be saved to your palette 🙂

make_17

Now you’ll always be able to choose these colors without remembering any HEX codes.

Setting background colors in Swift code

Sometimes you’ll need to set the background color in Swift code. This could be for a variety of different reasons. Perhaps your app is a game that has a changing color background based on the user’s play. Or maybe you have an element that you wrote purely in code and it doesn’t have a .XIB file.

The code to change a background element in Swift is relatively simple. To change the background color to blue in a Swift UIViewController, use the following code snippet:

self.view.backgroundColor = UIColor.blue

You can easily put this code inside a button handler or when an event happens to change colors based on user interaction.

UIColor is provided by Apple and has the following built in colors:

  • black
  • blue
  • brown
  • clear
  • cyan
  • darkGray
  • gray
  • green
  • lightGray
  • magenta
  • orange
  • purple
  • red
  • white
  • yellow

It’s nice that Apple has provided some built-in colors for developers to use, but what if you want to use custom colors?

How to set custom background colors in Swift

To set custom background colors in Swift code we must first understand what HEX color codes are. The format #ffffff are 3 color components in hexadecimal notation. The first part is red is ff, the second is green ff, and the last is blue ff. You can write hexadecimal notation in Swift using 0x prefix.

To make it simple to create UIColors from HEX values, lets create a helper initializer. Add the following code to a file named UIColor+Hex.swift

extension UIColor {
   convenience init(red: Int, green: Int, blue: Int) {
       assert(red >= 0 && red <= 255, "Invalid red component")
       assert(green >= 0 && green <= 255, "Invalid green component")
       assert(blue >= 0 && blue <= 255, "Invalid blue component")

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
   }

   convenience init(rgb: Int) {
       self.init(
           red: (rgb >> 16) & 0xFF,
           green: (rgb >> 8) & 0xFF,
           blue: rgb & 0xFF
       )
   }
}

Now you can simply create UIColors from HEX value like so:

let whiteColor = UIColor(rgb: 0xFFFFFF)
self.view.backgroundColor = whiteColor

To change the opacity or the alpha of a color, simply use the .withAlphaComponent method on your color. For example:

let whiteColor50Percent = UIColor(rgb: 0xFFFFFF).withAlphaComponent(0.5)
self.view.backgroundColor = whiteColor

This will create the color white with an opacity of 50%.

You can set the background colors of labels, buttons and other elements following a similar pattern in Swift code. Here are some examples to illustrate.

import UIKit

class BlueViewController: UIViewController {

    @IBOutlet weak var labelWithWhiteBg: UILabel!
    @IBOutlet weak var buttonWithRedBg: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blue
        labelWithWhiteBg.backgroundColor = UIColor.white
        buttonWithRedBg.backgroundColor = UIColor.red
    }
}

And this is what the app looks like on the simulator:

make_18

How to choose colors for your iOS app

There are many different ways to select a color scheme for your iOS app. However, there are some guidelines that Apple provides to make this process a little easier.

How to use color in your iOS app:

  • Use color judiciously for communication
  • Use complementary colors throughout your app
  • Choose a limited color palette that coordinates with your app logo
  • Pick a key color for interactivity throughout your app
  • Avoid using the same color for interactive and non-interactive elements
  • Test your app’s color scheme under a variety of lighting conditions
  • Use sufficient color contrast ratios

Each color has a purpose. If you use bright red or orange to indicate a problem or an error, don’t use it for something else – that could lead to miscommunication with the user.

Colors should work together and be easy on the eyes. Don’t use conflicting colors that don’t make sense together. Picking complementary colors on the color wheel makes this easy.

Pick a consistent color palette for your app logo and company brand. This is a good way to ensure your branding remain consistent and helps the user associate this palette with your company or app.

Interactive and non-interactive elements should be clearly different colors. This allows the user to learn what elements can be interactive and which ones are not. For example, yellow in Apple’s note app is the interactive color, anything that is yellow is clickable. This keeps communication clear with the user.

Be aware of how your app looks in different light. Test your app inside and outside. During sunny days and cloudy days. Be sure it also looks good in dark settings, such as dim bar or a candle-lit restaurant.

Colors should contrast enough and not be too similar. If colors are too similar, it can make reading and using your application a pain. The text may too easily blend into the background and users may find themselves confused. It is also important to think about color-blindness and how those users can use your application.

Preview your app on different devices. Your application colors may look different on different screens. Be sure to test on a wide variety of devices that your application supports.

Where to find automatically generate color schemes?

Here’s a list of websites that can automatically generate color schemes:

Be sure to use your own judgement when selecting a color scheme. Think about how you want your brand or app represented and choose accordingly.

What colors should I use for my iOS app? Ultimately, it is up to you to decide. It is recommend that you use colors that are coordinated with your app logo. Use different colors for interactive vs non-interactive elements.

How do I lower the transparency of colors in my iOS app? When you’re selecting colors either in the color wheel or the color slider, there be a opacity slider. You can set this from 0% to 100%.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts