13
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Storyboard上でViewにプロジェクトで定義した色を指定する方法

Last updated at Posted at 2015-09-09

Problem

  • Storyboard上で、UILabelに独自に定義したUIColorを指定したい

Solution

  • カラークラスを作成する。そしてcolorCodeからUIColorを取得するためのメソッドを定義しておく。
MyColor.swift
extension UIColor {
  convenience public init(hex: Int, alpha: CGFloat = 1.0) {
    let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
    let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
    let blue = CGFloat((hex & 0xFF)) / 255.0
    self.init(red:red, green:green, blue:blue, alpha:alpha)
  }
}

public struct MyColor {
  public static let Gray      = UIColor(hex: 0x808080)
  public static let RoyalBlue = UIColor(hex: 0x416931)

  static func fromCode(code: String) -> UIColor {
    switch code {
    case "Gray"      : return Gray
    case "RoyalBlue" : return RoyalBlue
    default:
      return UIColor.whiteColor()
    }
  }
}

  • カスタムLabelを作成し、backgroundColorCodetextColorCodeをStoryboard上で指定できるようにする
MyLabel.swift
import UIKit

@IBDesignable
class MyLabel: UILabel {
  @IBInspectable internal var backgroundColorCode: String = "" {
    didSet {
      backgroundColor = MyColor.fromCode(backgroundColorCode)
    }
  }
  
  @IBInspectable internal var textColorCode: String = "" {
    didSet {
      textColor = MyColor.fromCode(textColorCode)
    }
  }
}
  • StoryboardでUILabelを選択した状態でIdentity Inspectorを開き、Classを「MyLabel」にする
  • Attribute Inspectorを開き、BackgroundColorCodeを「RoyalBlue」にして、storyboardを保存する。
  • Storyboard上でUILabelの背景色が青になったら成功です。
13
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?