如果我将图像添加到UITextView中,如下所示:
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = image;
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[myString appendAttributedString:attrStringWithImage];
self.inputTextView.attributedText = myString;
如何通过用户点击键盘上的后退按钮来检测图像是否已被删除?
我会使用下面的内容吗?
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
若然,怎么样?
答案 0 :(得分:1)
我这样做了:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
[self.textView.attributedText enumerateAttribute:NSAttachmentAttributeName
inRange:NSMakeRange(0, self.textView.attributedText.length)
options:0
usingBlock:^(id value, NSRange imageRange, BOOL *stop){
if (NSEqualRanges(range, imageRange) && [text isEqualToString:@""]){
//Wants to delete attached image
}else{
//Wants to delete text
}
}];
return YES;
}
希望,能帮到你!
答案 1 :(得分:1)
使用swift,这是我从UITextView中删除图像(添加为NSTextAttachment)的方式:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// empty text means backspace
if text.isEmpty {
textView.attributedText.enumerateAttribute(NSAttachmentAttributeName, inRange: NSMakeRange(0, textView.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { [weak self] (object, imageRange, stop) in
if NSEqualRanges(range, imageRange) {
self?.attributedText.replaceCharactersInRange(imageRange, withString: "")
}
}
}
return true
}