我正在尝试将图像作为NSTextAttachment
添加到UITextField
,但是我得到的只是,
自定义UITextField
中的代码:
let myAttachment = NSTextAttachment()
myAttachment.image = myImage
myAttachment.bounds = CGRect(origin: .zero, size: myImage.size)
let myImageString = NSAttributedString(attachment: myAttachment)
let updatedText = NSMutableAttributedString()
updatedText.append(myImageString)
let myTextString = NSAttributedString(string: ", " + (self.text ?? ""))
updatedText.append(myTextString)
self.attributedText = updatedText
答案 0 :(得分:1)
UITextField
不允许NSTextAttachment
,但UILabel
允许NSTextAttachment
。
例如:
let attachment = NSTextAttachment()
let imageTest = UIImage(named:"user.png")
attachment.image = imageTest
let myString = NSMutableAttributedString(string: "My text ")
let myStringWithImage = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
myStringWithImage.append(myString)
myTextField.attributedText = myStringWithImage
myLabel.attributedText = myStringWithImage
这个苹果thread中没有答案。按照我的想法,我们可以在文本字段中输入表情符号,但不能在文本附件中输入表情符号。在文本字段中,我们为用户提供了输入文本的灵活性。
您可以使用leftView
中的UITextField
来显示图像。
答案 1 :(得分:0)
您是正确的,NSTextAttachment
中没有出现UITextField
,我不确定是错误还是UITextField
的错误,我将在此处提出雷达并更新响应:
同时,如果您可以将UI元素更改为UILabel
和UITextView
,请访问以下工作文件:
let attachment = NSTextAttachment()
attachment.image = myImage
attachment.bounds = CGRect(origin: .zero, size: myImage.size)
let attributedStr = NSMutableAttributedString(string: self.text ?? "")
attributedStr.insert(NSAttributedString(attachment: attachment), at: 0)