LoginSignup
2
2

More than 3 years have passed since last update.

【Swift】テキストに取り消し線を付ける

Posted at

NSAttributeString を使って文字列を装飾するやり方をまとめました。

完成図

実装

@IBOutlet weak var textLabel: UILabel!

private func setTestLabel() {
    // 表示したいテキスト
    let text = "文章の中の一部に取り消し線を付けたい。"
    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: text)
    // 全体に共通して付けたいレイアウトを設定
    attributeString.addAttribute(.font,value: UIFont.systemFont(ofSize: 15), range: NSMakeRange(0, attributeString.length))

    // 取り消し線部分の設定
    attributeString.addAttributes([
        .foregroundColor : UIColor.red,
        // 取り消し線の太さを決める
        .strikethroughStyle: 1
    // 取り消し線を反映したい部分を設定
    // NSMakeRange(何文字目から, 何文字間)
    ], range: NSMakeRange(8, 5))
    textLabel.attributedText = attributeString
}

// NSMakeRange(何文字目から, 何文字間)はこんな感じにも書き換えられる
// こちらの方が直感的でわかりやすい
NSString(string: text).range(of: "取り消し線")

これで取り消し線の実装は完了です👌

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