小编kno*_*ane的帖子

如何使用nsattributedstring在Swift中将图像添加为文本附件

我正在尝试使用我作为按钮放入的图像为iOS构建自定义键盘.当我按下按钮时,链接到该按钮的图像被放入一个属性字符串,该字符串被加载到自定义键盘视图内的UiTextView中.那很有效.

问题是,当我将新图像附加到属性字符串时,字符串中的旧图像和新图像都将更改为我当前按下的图像.我无法理解为什么字符串中的旧图像正在发生变化.

有什么建议?我已经尝试使用replaceCharactersInRange和insertAttributedString但无法使其工作.这是代码(在viewDidLoad之后):

let textAttachment = NSTextAttachment()

let textView = UITextView(frame: CGRectMake(5, 5, 200, 40))
var attributedString = NSMutableAttributedString(string: "")

@IBAction func buttonPressed(button :UIButton) {

    let string = button.titleLabel?.text

    textAttachment.image = UIImage(named: "\(string!).png")!
    textAttachment.image = UIImage(CGImage: textAttachment.image!.CGImage!, scale: 6, orientation: .Up)
    let attrStringWithImage = NSAttributedString(attachment: textAttachment)
    attributedString.appendAttributedString(attrStringWithImage);


    textView.attributedText = attributedString;
  }
Run Code Online (Sandbox Code Playgroud)

谢谢!

iphone ios swift ios-app-extension custom-keyboard

9
推荐指数
2
解决办法
9258
查看次数

标签 统计

custom-keyboard ×1

ios ×1

ios-app-extension ×1

iphone ×1

swift ×1