6

如果我像这样将图像添加到 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

如果是这样,怎么做?

4

2 回答 2

3

我这样做了:

- (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;
}

希望,能帮到你!

于 2015-10-27T19:07:10.477 回答
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
}
于 2016-03-29T01:55:16.157 回答