2012-08-12 51 views
2

我有一個UITableView,它有一些單元格,我向每個單元格添加UITextFieldUITextField的清除按鈕在UITableViewCell中不工作

我設置了textField.clearButtonMode = UITextFieldViewModeWhileEditing

當我編輯textField時,清除按鈕和鍵盤都出來了。我在textField中鍵入一些單詞,然後點擊清除按鈕,鍵盤將被隱藏,但textField中的文本不會被清除。

除了清除按鈕外,其他所有功能都可以正常工作。

回答

7

我有這個問題,因爲我已經忘記了我使用的是UITapGestureRecognizer趕在桌子上水龍頭駁回鍵盤和它捕獲的清除按鈕水龍頭,阻止其運行。在UITapGestureRecognizer上添加cancelsTouchesInView=NO以使觸摸仍然生效,並使用CGRectContainsPoint上的tapper方法僅檢查結束編輯,並且僅在當前的UITextField的幀矩形上沒有敲擊時檢查resignFirstResponder。請注意,這仍然不完全完美,因爲在自動更正上輕擊X可能不在文本框的框架矩形之外,因此檢查單元格contentView會更好。

+0

與你一樣,我還使用UITapGestureRecognizer來捕捉表上的水龍頭。謝謝 – huuang 2012-08-31 10:09:21

+0

應該在哪裏執行cancelsTouchesInView = NO?在tap方法中? – 2013-05-30 12:01:22

+0

更完整的例子會很好;-) – 2013-05-30 12:20:23

1

我無法重現您遇到的問題,因爲觸摸「清除」按鈕不會也不應該放棄第一響應者。但是也許你可以將你的代碼與我在下面包含的最基本的用例進行比較,以便找出哪裏出了問題。

此外,我會建議閱讀有關UIResponder的文檔,因爲它似乎可能會意外地涉足此區域。

@implementation TextFieldTableViewController 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return 5; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 

    // Remove old instances of myTextField 
    for (UIView *oldView in cell.contentView.subviews) 
     [oldView removeFromSuperview]; 

    // Create my new text field 
    UITextField *myTextField = [[UITextField alloc] initWithFrame:cell.contentView.bounds]; 
    [myTextField setClearButtonMode:UITextFieldViewModeWhileEditing]; 
    [myTextField setBorderStyle:UITextBorderStyleRoundedRect]; 

    // Add the TextField to the content view 
    [cell.contentView addSubview:myTextField]; 

    return cell; 
} 

@end 
1

如果你有手勢識別器,你應該做這樣的方式

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(methodThatYouMayCall)]; 
[myTextField addGestureRecognizer:gestureRecognizer]; 
gestureRecognizer.delegate = self; 
gestureRecognizer.cancelsTouchesInView = NO; 

,這將清除文本框以及火災「methodThatYouMayCall」當你點擊清除按鈕,這樣你應該這樣做,以及 您textField.clearButtonMode是一種UIButton的類,這樣就可以做到這一點的方式

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch 
{ 
    if ([touch.view isKindOfClass:[UIButton class]]) 
    { 
     return NO; 
    } 
    else 
    { 
     return YES; 
    } 
} 

不要忘記將類標記爲實現UIGestureRecognizerDelegate協議。希望這會幫助你。

相關問題