2014-11-02 48 views
0

在我的類中使用shouldChangeCharactersInRange來捕獲UITextField在uitableview中。shouldChangeCharactersInRange返回UITextField的第二個字符

問題是它沒有得到第一個輸入值並從第二個開始。

如果我輸入 「123」,它僅示出了 「12」

這是我的代碼:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    UITextField *utx = (UITextField *) textField; 

    UITableViewCell *cell = (UITableViewCell*)utx.superview.superview.superview; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    UITextField *utxtest = (UITextField *)[cell.contentView viewWithTag:20]; 

    NSLog(@"utxtest %@", utxtest.text); 
     NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet]; 

     NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; 

     return [string isEqualToString:filtered]; 

    return YES; 
} 

,在我的tableview:

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    UITextField * utxtest = (UITextField *)[cell.contentView viewWithTag:20]; 
    utxtest = self; 
    return cell; 
} 
+0

當你說,而不是'123'它顯示'23',那是什麼?在NSLog語句中還是在UITableViewCell中? – AMI289 2014-11-02 10:30:32

+0

它在nslog輸出「utxtest 23」 – 2014-11-02 10:32:54

+0

它顯示如果你NSLog的utx變量是什麼? – AMI289 2014-11-02 10:44:22

回答

1

我與的UITextField和測試將NSLog放在shouldChangeCharactersInRange上,就像你所做的一樣。輸入「123」,nslog顯示「12」,而不是「23」,正如你所說。

所以首先,重新檢查你的結果。如果它仍然是「23」,我不知道它

如果它是「12」,我認爲問題是你把您的NSLog上shouldChangeCharactersInRange它負責輸入文本驗證。文本字段僅分配新值,僅在AFTER此方法返回YES。如果返回NO,則該值不會改變。而當然,當你仍然處在方法的中間時,textfield.text仍然返回舊值。

+0

非常感謝,我修好了,你的權利。這是一個錯字,結果是「12」而不是「23」。所以有什麼辦法可以捕獲完整插入文本shouldChangeCharactersInRange內? – 2014-11-02 10:49:32

+1

我沒有XCode在這裏測試,但你可以嘗試NSString * tmpNewValue = [utxtest.text stringByReplacingCharactersInRange:range withString:string]; //這裏的字符串是replacementString的值。請記住,您只需獲取新的臨時值,不要在此方法中更改utxTest的值,這會導致副作用 – meaholik 2014-11-02 14:42:05

相關問題