LoginSignup
5
3

More than 5 years have passed since last update.

iOSのLabelの文字間隔を指定可能にする (Swift 4.2)

Posted at

Labelの文字間隔

iOS開発において、 Label による文字列の間隔を変更したいケースがあります。これは NSAttributedString.Key.kern を使用することで変更することが可能です。

"kern" はテキストにおける文字同士の間隔を意味するものであり、このプロパティに値を設定すると、文字列の間隔が調整可能となります。このデフォルト値は 0 であり、カーニング、つまり文字間隔が指定されていない状態です。文字間隔を広げる場合は0以上、文字間隔を狭める場合は0以下の値を指定します。

コーディング例

stackoverflowの回答 を参考にして、文字間隔を指定可能なカスタムLabelクラスを作ってみます。

CustomLabel.swift
import UIKit

open class CustomLabel: UILabel {
    @IBInspectable open var spacing:CGFloat = 0 {
        didSet {
            let attributedString = NSMutableAttributedString(string: self.text!)
            attributedString.addAttribute(NSAttributedString.Key.kern, value: self.spacing, range: NSRange(location: 0, length: attributedString.length))
            self.attributedText = attributedString
        }        
    }
}

作成した CustomLabel をビューに配置したLabelに適用します。

image.png

Inspectorに Spacing の設定項目が表示されるので、任意の値を設定します。

image.png

すると、次のようにSpacingに設定した値に応じて、文字間隔が変更されます。

Spacing=0
image.png

Spacing=10
image.png

参考

How do I change the letter spacing in a UILabel?

5
3
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
5
3