Chris
Chris

Reputation: 2274

Swift - add custom color from Storyboard programmatically

I have a custom made color in Storyboard. Is there a way to access it via code? Couldn't find anything on that topic.

enter image description here

I know there is a way to code custom-colors in Swift like this:

view.backgroundColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 1.00)

But getting my exact color with that method will take ages. Any suggestions?

UPDATE

I got it working with the RGB slider but my collectionView still appears white. That's my code:

    let theCollectionView: UICollectionView = {
    let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
    v.translatesAutoresizingMaskIntoConstraints = false
    v.backgroundColor = UIColor(red: 50, green: 215, blue: 200, alpha: 1)
    v.contentInsetAdjustmentBehavior = .always
    v.layer.cornerRadius = 30
    return v
}()

Upvotes: 2

Views: 4154

Answers (1)

vacawama
vacawama

Reputation: 154513

You have a couple of ways to do this.

  1. Drag the color patch directly into the code. This will add a #colorLiteral which will show as a little colored patch right in the code. Clicking on the color patch will open the color picker. If you want to see the values for the red, green, blue and alpha, just comment out that line of code.
  2. You can view the color using the RGB Sliders in the color picker. Choose the Sliders icon (second from the left) and choose RGB Sliders from the popup. To put the RGB values into your code, you need to divide the values by 255.0 because the range needed by UIColor is 0...1 not 0...255. So for RGBA(50, 215, 200, 1), the value would be:

    UIColor(red: 50.0/255.0, green: 215.0/255.0, blue: 200.0/255.0, alpha: 1) 
    

Upvotes: 2

Related Questions