2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】UILabelに取り消し線を引くには

Last updated at Posted at 2021-02-14

はじめに

アプリ開発をしていく中で、UILabelに取り消し線を表示させたいと思い調べたのでご紹介します。

開発環境

  • macOS Catalina version10.15.7
  • Xcode version12.2
  • Swift5

NSMutableAttributedString

取り消し線を実装するには、NSMutableAttributedStringを使用します。

NSMutableAttributedStringとは?

NSMutableAttributedStringは、属性付きの文字列コンテンツを変更するための追加メソッドを宣言しているクラスとのこと。このクラスを用いて、属性の変更(今回であれば、取り消し線の追加)を行う。

属性の追加は、addAttribute()を使用する。このメソッドより、どういった属性を対象の文字列のどの範囲に追加するかを設定する。

参考
NSMutableAttributedString
addAttribute:value:range:

実装と解説

全体コード

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "対象の文字列")
            
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) 
            
Label.attributedText = attributeString

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "対象の文字列")

こちらの処理で、NSMutableAttributedTextを宣言している。


attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) 

こちらの処理で属性を追加している。addAttribute()メソッドを用いて、追加したい属性や適用範囲を指定する。
addAttribute()メソッドでは3つの引数を指定する。

・name:属性名を指定する
属性名に関しては、今回テキスト属性を指定するためNSAttributedStringKeyを使用する。その中で、取り消し線を実装したいためstrikethroughStyleを指定する。

・value:属性値を指定する
初期値が0で、数値を大きくすると取り消し線の太さが太くなる。

・range:対象の文字列への適用範囲を指定する
今回は、対象の文字列全体に取り消し線を追加したいためNSMakeRange()を用いて文字列全体を範囲として指定している。

参考
strikethroughStyle
NSAttributedTextやNSMutableAttributedTextの使い方


Label.attributedText = attributeString

最後に属性付きの文字列を、UILabelに反映させてあげれば完了。

こんな感じになります。
スクリーンショット 2021-02-11 16.47.57.png

まとめ

今回は、取り消し線を実装するにあたり調べてみたことをまとめてみました。

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?