LoginSignup
3
2

More than 5 years have passed since last update.

NSUnderlineStyleでUILabelに下線を引いた結果まとめ

Posted at

概要

NSUnderlineStyleを使ってUILabelに下線を引いた結果の表示内容がどこにもまとまってなかったので、軽くまとめてみました。
雑なサンプルですが何かの役にたてば。

検証コード

override func viewDidLoad() {
    super.viewDidLoad()

    let single = NSUnderlineStyle.styleSingle.rawValue
    let thick = NSUnderlineStyle.styleThick.rawValue
    let double = NSUnderlineStyle.styleDouble.rawValue

    let dot = NSUnderlineStyle.patternDot.rawValue
    let dash = NSUnderlineStyle.patternDash.rawValue
    let dashDot = NSUnderlineStyle.patternDashDot.rawValue
    let dashDotDot = NSUnderlineStyle.patternDashDotDot.rawValue

    let word = NSUnderlineStyle.byWord.rawValue

    addUnderLine(label: singleDot, setValue: single | dot)
    addUnderLine(label: singleDash, setValue: single | dash)
    addUnderLine(label: singleDashDot, setValue: single | dashDot)
    addUnderLine(label: singleDashDotDot, setValue: single | dashDotDot)

    addUnderLine(label: thickDot, setValue: thick | dot)
    addUnderLine(label: thickDash, setValue: thick | dash)
    addUnderLine(label: thickDashDot, setValue: thick | dashDot)
    addUnderLine(label: thickDashDotDot, setValue: thick | dashDotDot)

    addUnderLine(label: doubleDot, setValue: double | dot)
    addUnderLine(label: doubleDash, setValue: double | dash)
    addUnderLine(label: doubleDashDot, setValue: double | dashDot)
    addUnderLine(label: doubleDashDotDot, setValue: double | dashDotDot)

    addUnderLine(label: byWord, setValue: thick | word)
}

private func addUnderLine(label: UILabel, setValue: Int) {
    let attributeText = NSMutableAttributedString(string: label.text!)
    attributeText.addAttribute(.underlineStyle, value: setValue, range: NSMakeRange(0, label.text!.count))
    label.attributedText = attributeText
}

結果

NSUnderlineStyle_sample.png

補足(環境)

  • Xcode9.4
  • iPhone X
  • System Font 17

感想

基本的には想定通りの下線付与結果になったが結構文字と近い状態で線が引かれてしまうので、1dotのviewなどを使って擬似的に自分で線を引いた方が良いかもしれません。
byWordに関しては、スペース部分を無視してくれるという特性は自分で実装すると少し面倒なので役に立ちそうです。

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