LoginSignup
19
11

More than 5 years have passed since last update.

SketchとXcodeのlineSpacingの定義が違ってデザインに手こずった話

Posted at

SketchのlineSpacingを、XcodeでもlineSpacingとして指定するとデザインが異なり手こずった。
結論を先に言うとXcodeのlineSpacingは、(SketchのlineSpacing) - (フォントサイズ) を指定し、かつUILabel自体のY PositionをlineSpacingの半分、下げる

XcodeのlineSpacingの定義

The distance in points between the bottom of one line fragment and the top of the next.

すなわち行の下から次の行の上までの距離です。
https://developer.apple.com/documentation/uikit/nsmutableparagraphstyle/1528742-linespacing

XcodeのlineHeightMultipleの定義

The line height multiple.

すなわち行の高さです
https://developer.apple.com/documentation/uikit/nsparagraphstyle/1528614-lineheightmultip

SketchのlineSpacingの定義

image.png
image.png
SketchのlineSpacingは、フォントの実体としてのサイズ+行間の空白のサイズです
そのため上の画像のように行の中心から次の行の中心が30ptとなっていることが分かります
http://gomaapps.blogspot.com/2015/07/sketch_20.html

lineSpacing、lineHeightMultipleとSketchのlineSpacingの略図

IMG_8749.jpg

XcodeとSketchのlineSpacingの開始行のポイントの違い

スクリーンショット 2018-12-12 14.05.06.png
以上を踏まえSketchのlineSpacingからFontSizeを引いた値をXcodeでlineSpacingとして指定してみる。
それでもSketchに比べXcodeのlineSpacingではテキストの開始行が下がっていることが分かる。

現実的な対処方法

XcodeのlineSpacingは、(SketchのlineSpacing) - (フォントサイズ) を指定し、かつUILabel自体のY PositionをlineSpacingの半分、下げる
スクリーンショット 2018-12-12 14.41.18.png

 ###ちなみに実装では、以下のようなUILabel+Extension.swiftで指定していた

UILabel+Extension.swift
extension UILabel {

    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // (Swift 4.2 and above) Line spacing attribute
        attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))


        // (Swift 4.1 and 4.0) Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString
    }
}

参考
https://stackoverflow.com/questions/39158604/how-to-increase-line-spacing-in-uilabel-in-swift/39158698
上記のようなUILabel+Extensionを利用した。

19
11
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
19
11