在UITextView中模拟按键的性能问题

时间:2011-04-02 02:06:10

标签: iphone performance uitextview keypress

我使用以下代码模拟UITextView中的按键(以及将滚动设置为插入位置):

NSRange selectedRange = textview.selectedRange;

NSString *currentText = textview.text;

NSString *yourString = @"x";

NSString *firstPart = [currentText substringToIndex: selectedRange.location];
NSString *lastPart = [currentText substringFromIndex: selectedRange.location];

NSString *modifiedText = [firstPart stringByAppendingFormat:@"%@%@", yourString, lastPart];

textview.text = modifiedText;

NSInteger loc = selectedRange.location + 1;
NSInteger len = textview.selectedRange.length;

NSRange newRange = NSMakeRange(loc, len);
textview.selectedRange = newRange;

正如你所看到的,我划分了textview.text,我在光标位置插入了@“x”,我修改了整个文本。事实上,这很有效,除非文本文件的长度很大。这听起来合乎逻辑,因为我将整个事物分成几部分,所以每个模拟键都是如此。

因此,对于一个小文本文件我没有任何问题,但有一个大文本我可以看到相当滞后。

有没有办法以更好的表现来做到这一点?

1 个答案:

答案 0 :(得分:4)

不应在每次击键时重写整个文本,而应使用
-(void)insertText:(NSString*)text方法

来自here的示例代码:

@interface UIResponder(UIResponderInsertTextAdditions)
- (void) insertText: (NSString*) text;
@end

@implementation UIResponder(UIResponderInsertTextAdditions)

- (void) insertText: (NSString*) text
{
    // Get a refererence to the system pasteboard because that's
    // the only one @selector(paste:) will use.
    UIPasteboard* generalPasteboard = [UIPasteboard generalPasteboard];

    // Save a copy of the system pasteboard's items
    // so we can restore them later.
    NSArray* items = [generalPasteboard.items copy];

    // Set the contents of the system pasteboard
    // to the text we wish to insert.
    generalPasteboard.string = text;

    // Tell this responder to paste the contents of the
    // system pasteboard at the current cursor location.
    [self paste: self];

    // Restore the system pasteboard to its original items.
    generalPasteboard.items = items;

    // Free the items array we copied earlier.
    [items release];
}

@end