LoginSignup
20
14

More than 5 years have passed since last update.

【Swift】UILabel に UIImage を表示する方法

Last updated at Posted at 2018-12-12

よくアイコンなどを、ラベルの前や後ろに付けたいという時があると思います。
そんな時に、役立つ NSAttributedString を使った、UILabel に UIImage を表示する方法を紹介しようと思います。

はじめに

文字の後ろに画像を追加したい際、画像のように UILabel の横に UIImageView を置くことを考えると思います。
しかし、文字が1行で収まる場合は良いかもしれませんが、複数行になった場合は文字のすぐ後ろに画像をつけることができません。
うまくいかない.png

開発環境

  • Xcode 9.4
  • Swift 4.1

NSAttributedString を用いて画像を UILabel に表示

NSAttributedString は、フォントや文字色などを変更する時に使いますが、画像も表示することができます。

使い方は簡単

UIImageをNSAttributedStringにして返す
func converUseImage(image: UIImage) -> NSAttributedString {

        let attachment = NSTextAttachment()

        // 指定 image の追加
        attachment.image = image

        // image を1行分の高さにするための係数
        let k = image.size.height / oneLineHeight

        // y は自分で調整するしかないかもしれません
        attachment.bounds = CGRect(x: 0, y: -5, width: image.size.width/k, height: image.size.height/k)

        return NSAttributedString(attachment: attachment)
}

表示したいの画像サイズにより UILabel のレイアウトが崩れてしまうため、bounds の y の値や画像サイズの調整をしなければなりません。今回は、画像の高さがラベル1行分の高さで収まるように k という係数を求め、幅と高さを割っています。
サンプルのように画像の高さを一定になるように調整し y の値を定数にするか、画像サイズから y の値を計算する方法を考える必要があります。

実際の使い方としては、NSMutableAttributedString() に NSAttributedString()を追加し、UILabel に代入します。

ラベルに追加
        let attributedText = NSMutableAttributedString()
        attributedText.append(NSAttributedString(string: "あなたのチームのアイコンはうさぎです。この文章の後ろに表示されている画像がチームのアイコンになります。"))
        // UIImage で画像を作成
        attributedText.append(setImgaeInLabel(image: UIImage(named: "rabbit")!))
        // attributedText に追加
        label.attributedText = attributedText

使用例

高さを1行に揃えた時 高さを大きくした時(yの値も変えています)
sample1.png sample2.png
間に画像 端に画像
Simulator Screen Shot - iPhone 7 - 2018-12-07 at 16.26.21.png sample3.png

参考

20
14
1

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
20
14