ios - 防止在 shouldChangeTextInRange 期间删除前缀

标签 ios cocoa-touch uitextview

我有一个 UITextView,它有一个包含 4 个字符的空白字符串作为缩进的前缀。如果我输入大量文本然后按住退格键大约一秒钟,它会逐字逐句快速删除文本,但它也会删除我的“分隔符空格”,这会导致我的 UITextView 卡住了,无法再打字了。

这就是我要说的问题:

if (range.location <= 4 && textView == self.descriptionTextView) {
    #warning fast deletion causes this to be un-editable
    return NO; // makes sure no one can edit the first 4 chars
}

如何防止这种“快速删除”也删除“分隔空间”?

最佳答案

为了维护您的前缀,我建议找出如果您实际上更改给定范围内的字符会产生的字符串,然后只允许在前缀不更改时更改文本保持原样;例如,在您的特定情况下:

- (BOOL)textView:(UITextView *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // Combine the new text with the old
    NSString *combinedText = [textView.text stringByReplacingCharactersInRange:range withString:string];

    // If the user attempts to delete before the 4th
    // character, delete all but the first 4 characters
    if (combinedText.length < 4) {
        textView.text = @"    "; // <-- or whatever the first 4 characters are
        return NO;
    }

    // Else if the user attempts to change any of the first
    // 4 characters, don't let them
    else if (![[textView.text substringToIndex:4] isEqualToString:[combinedText substringToIndex:4]]) {
        return NO;
    }

    return YES;
}

或者更一般地说,为了实现灵 active ,您可以将前缀字符串存储为类实例变量,然后将您的 shouldChangeCharactersInRange: 代码基于前缀变量可能是什么:

- (BOOL)textView:(UITextView *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // Combine the new text with the old
    NSString *combinedText = [textView.text stringByReplacingCharactersInRange:range withString:string];

    // If the user attempts to delete into the prefix
    // character, delete all but the prefix
    if (combinedText.length < self.prefixString.length) {
        textView.text = self.prefixString;
        return NO;
    }

    // Else if the user attempts to change any of the prefix,
    // don't let them
    else if (![self.prefixString isEqualToString:[combinedText substringToIndex:self.prefixString.length]]) {
        return NO;
    }

    return YES;
}

关于ios - 防止在 shouldChangeTextInRange 期间删除前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673079/

相关文章:

iOS TableView beginUpdates 视觉错误,黑色单元格

ios - Phonegap iOS应用被拒绝使用GPS

ios - 删除按钮位于 UITableView 样式分组单元格背景之外

objective-c - 在 UITableViewCell 中调整 UIImageView 的大小

iphone - 为什么这只是有时有效? (UITextView辞职第一响应者问题)

ios - 如何在 iPhone 4S Swift 上的 UITextView 中动态调整文本大小

ios - 在 Objective-C 中加载时将光标移动到预填充 Textview 的开头

ios - CKServerChangeToken 的 "scope"是什么?

ios - 我怎样才能找到谁在保留一个对象?

javascript - 将 "unsupported"设置为 div 内的数据集