1
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 5 years have passed since last update.

【Swift4】Labelに表記する単位をフォント小さめで表示する方法

Last updated at Posted at 2019-05-01

Swiftでラベルに何らかの数値と単位を表示する場面はよくあると思います。そのときに単位の部分だけフォントを小さく表示したいことが多いです。
ストーリーボード上で別のラベルとして分けてもいいのですが、ラベル間の間隔が空いてしまったりレイアウトが面倒だったりするので、コードで単位文字列だけフォント変更するようにしてみました。

image.png

NSMutableAttributedStringを使ったフォント変更

NSMutableAttributedStringを使うことで、複数の文字列それぞれに文字装飾を指定した後に、文字列を連結させることができます。

// 表示したいメインの文字列もNSMutableAttributedStringで定義
let pointString = NSMutableAttributedString(string: String(point))

// 単位文字列に指定したい要素を定義
let unitStringAttributes: [NSAttributedString.Key : Any] = [
    .foregroundColor : UIColor.black,
    .font : UIFont.boldSystemFont(ofSize: 11.0)
]

// 単位文字列を定義し、先ほどのattributeを指定
let unitString = NSMutableAttributedString(string: "ポイント", attributes: unitStringAttributes)

// NSMutableAttributedStringを作り、ここにappendして装飾文字列を連結
let pointLabelString = NSMutableAttributedString()
pointLabelString.append(pointString)
pointLabelString.append(unitString)

// ラベルに表示する際にはtextではなくattributedTextに代入
cell.taskPointLabel.attributedText = pointLabelString

上記の実装で以下のように表示されます。フォントの大きさだけでなく色や書体なども変えられるのでぜひ試してみてください。

image.png

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