【发布时间】:2015-12-22 16:27:24
【问题描述】:
我正在尝试使用我作为按钮放入的图像为 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;
}
【问题讨论】:
-
您为每个图像重复使用相同的
textAttachment,这是您的问题。每次只需创建一个新的NSTextAttachment(),无需存储。
标签: ios iphone swift ios-app-extension custom-keyboard