LoginSignup
27
15

More than 5 years have passed since last update.

字間(カーニング)に対応するUILabelを実装する(IBDesignable/IBInspectableを活用する)

Last updated at Posted at 2016-12-01

UILabelでカーニング(字間)に対応する必要があったため、いろいろ調べた所……。
こんな参考資料(StackOverflow)が見つかったので、早速やってみました!

スクリーンショット 2016-12-01 15.33.32.png

字間(カーニング)に対応したUILabelを実装する

KerningLabelを実装

まず、StackOverflowに則って、KerningLabel.swiftを実装します。
(Swift4対応してくださった@zizi4n5さんに感謝いたします!)

KerningLabel.swift
import UIKit
@IBDesignable
class KerningLabel: UILabel {
    @IBInspectable var kerning: CGFloat = 0.0 {
        didSet {
            if let attributedText = self.attributedText {
                let attribString = NSMutableAttributedString(attributedString: attributedText)
                attribString.addAttributes([.kern: kerning], range: NSRange(location: 0, length: attributedText.length))
                self.attributedText = attribString
            }
        }
    }
}
  • @IBDesignableでクラスの実装を始めると、Interface Builderでパラメータを調整できるViewを作ることができます!
  • @IBInspectableから書き始めて定義する箇所は、Interface Builderでパラメータ入力が可能になります!対応している型は下に書いておきます。

UILabelのCustom Classとして設定

実装が終わったら、Interface Builder側で作業です。
StoryboardやViewに置いたUILabelを選択し、Custom ClassにKerningLabelを設定します。

スクリーンショット 2016-12-01 15.13.13.png

好みのKerningを設定

Custom ClassにKerningLabelを設定すると、UILableのInspectionに「Kerning」の項目が追加されます。
あとは、好みのパラメータを設定すれば、完璧です!

スクリーンショット 2016-12-01 15.15.21.png

できたー!
ちなみにこの機能、Live Renderingって言うらしいよ!

IBInspectableが対応している型

なお、IBInspectableで対応している型は、以下の通りとのこと。

  • Int
  • CGFloat
  • Double
  • String
  • Bool
  • CGPoint
  • CGRect
  • UIColor
  • UIImage

このサイトがわかりやすい(We ❤ Swift
UI実装の作業効率も上がるし、なにより面白い!!

みなさんも、IBDesignableなクラスを実装して、UI実装を効率化しましょう!(これが結論?)

27
15
4

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
27
15