ios - 如何删除整个 NSAttributedString block

标签 ios uitextview nsattributedstring

我正在开发一款应用,让用户可以通过输入@用户名 来提及其他用户。虽然我有 found a way要检测 @ 字符并在文本字符串中突出显示所选用户名,我不确定如何在用户提及用户但随后想从提及中删除该用户时管理该事件。

例如,在 Facebook 应用程序中,当您提及某人时,UITextView 中该人的姓名会以浅蓝色背景突出显示。但是,当您开始删除该提及时,当您删除属性字符串中的最后一个字符时,整个提及都会被删除。

因此,我正在寻找一种方法,当用户删除属性字符串的最后一个字符以便删除整个属性字符串并从 TextView 中完全删除提及时,我可以捕获这种方法。

最佳答案

为了实现上述期望的行为,我最终执行了以下操作。我将所有这些方法实现为放置 UITextView 的 View Controller 的一部分,因此我将 UITextViewDelegate 协议(protocol)添加到我的 View Controller 。然后,我实现了以下方法:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //if this is true, then the user just deleted a character by using backspace
    if(range.length == 1 && text.length == 0){            
        NSUInteger cursorPosition = range.location; //gets cursor current position in the text
        NSRange attrRange; //will store the range of the text that holds specific attributes
        NSDictionary *attrs = [_content.attributedText attributesAtIndex:cursorPosition effectiveRange:&attrRange];

        //check if the attributes of the attributed text in the cursor's current position correspond to what you want to delete as a block
        if([attrs objectForKey:NSBackgroundColorAttributeName]){
            NSAttributedString *newStr = [_content.attributedText attributedSubstringFromRange:NSMakeRange(0, attrRange.location)]; //creates a new NSAttributed string without the block of text you wanted to delete
            _content.attributedText = newStr; //substitute the attributed text of your UITextView
            return NO;
        }
    }
    return YES;
}

关于ios - 如何删除整个 NSAttributedString block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30360502/

相关文章:

ios - 后台任务 swift 3.0 iOS

ios - 以编程方式更改 UINavigationBar 上的 UIBarButtonItem 标识符

ios - 收到 ARC 语义问题如何解决?

ios7 - 如何将 HTML 的 CSS 添加到 NSAttributedString?

ios - NSAttributedString指定范围?

ios - NSAttributedString boundingRectWithSize 为我的表格单元格返回错误的高度?

ios - 项目列表与数据源

iphone - 无法在 iOS6 中的 UITextField 或 UITextView 中输入文本

iOS Swift 2.0 UITextView 根据文本卡住应用程序

ios - 附加 NSAttributedStrings 返回错误