110

UITextView を使用して次の効果を得ようとしています。

ここに画像の説明を入力

基本的に、テキストの間に画像を挿入したい。画像は 1 行のスペースを占めるだけなので、ラッピングは必要ありません。

サブビューに UIView を追加してみました:

UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[pictureView setBackgroundColor:[UIColor redColor]];
[self.textView addSubview:pictureView];

しかし、それはテキストの上に浮かんでいて、それを覆っているようです.

これを実装する1つの方法と思われる除外パスについて少し読みました。ただし、画像を絶対に配置したくはありません。代わりに、テキストとともに流れる必要があります ( <span>HTML での動作と同様)。

4

5 に答える 5

28

@bilobatum のコードは、必要な人のために Swift に変換されています。

let attributedString = NSMutableAttributedString(string: "like after")

let textAttachment = NSTextAttachment()

textAttachment.image = UIImage(named: "whatever.png")

let attrStringWithImage = NSAttributedString(attachment: textAttachment)

attributedString.replaceCharacters(in: NSMakeRange(4, 1), with: attrStringWithImage)
于 2016-01-19T22:52:58.043 に答える
5

簡単な例での問題解決は ここに画像の説明を入力

let attachment = NSTextAttachment()
attachment.image = UIImage(named: "qrcode")

let iconString = NSAttributedString(attachment: attachment)
let firstString = NSMutableAttributedString(string: "scan the ")
let secondString = NSAttributedString(string: "QR code received on your phone.")

firstString.append(iconString)
firstString.append(secondString)

self.textLabel.attributedText = firstString
于 2018-06-29T18:04:20.490 に答える