2011-05-15 20 views
3

我遇到了一個問題,那就是當在鍵盤上保留刪除鍵時,iOS給我的UITextViewDelegate不正確的信息。退格鍵HELD Down時的UITextViewDelegate行爲

當用戶HOLDS在iPad上一個UITextView Delete鍵的UITextView將開始刪除整個單詞,而不是它被按下單個字符長(注:這不會在模擬器中進行)。

當發生這種情況時,UITextView的委託方法:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 

被調用與由正確的光標位置的範圍內,但長度爲1。這是不正確的的UITextView現在刪除整個詞語,不是單個字母。例如,下面的代碼將只打印一個空格。

[textView substringWithRange:range] 
string contains " " 

儘管UITextView刪除了整個單詞。替換文本正確地作爲空字符串給出。有沒有人知道這個問題的解決方案或解決方法?

+0

這個西梅恩的運氣怎麼樣?有沒有辦法阻止「按字刪除」操作? – typeoneerror 2011-09-30 22:08:01

+0

我仍然無法找到一種方法來阻止它(或讓它將正確的數據提交給委託人),但是能夠檢測到它使我能夠解決該錯誤。 – simeon 2011-10-02 01:14:16

+1

請注意,UITextViewDelegate還有一個額外的錯誤。如果在設置中將「常規」 - >「輔助功能」 - >「三次點擊」設置爲「VoiceOver」或「詢問」,則UITextViewDelegates將爲任何標點符號收到重複的「shouldChangeTextInRange」消息。這是非常難以追查的。 – simeon 2011-10-02 01:15:30

回答

3

雅各布提到我應該發佈這個答案。所以在這裏。

我對此的駭客解決方法是監視shouldChangeTextInRange中給出的文本長度和範圍,然後將其與textViewDidChange中的文本長度進行比較。如果差異不同步,我刷新我的支持文本緩衝區,並從文本視圖重建它。這不是最佳的。這裏是我的臨時解決方法:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{ 
    //Push the proposed edit to the underlying buffer 
    [self.editor.buffer changeTextInRange:range replacementText:text]; 

    //lastTextLength is an NSUInteger recording the length that 
    //this proposed edit SHOULD make the text view have 
    lastTextLength = [textView.text length] + ([text length] - range.length); 

    return YES; 
} 

- (void)textViewDidChange:(UITextView *)textView 
{ 
    //Check if the lastTextLength and actual text length went out of sync 
    if(lastTextLength != [textView.text length]) 
    { 
     //Flush your internal buffer 
     [self.editor.buffer loadText:textView.text]; 
    } 
}