2010-08-09 88 views
3

我有一個文本字段在UITableViewCell中顯示,我希望能夠隱藏鍵盤時,用戶觸摸屏幕上除了文本字段以外的任何地方。我知道[field resignFirstResponder],但我不知道如何攔截UITableView背景上的觸摸以調用「resignFirstResponder」。如何讓鍵盤消失?

任何幫助將不勝感激。

回答

3

要做到這一點的唯一方法是繼承UITableView,在子類UITableView中實現touchesBegan方法並將UITextField對象發送給UITableView。下面是它看起來應該像 -

// GRTableView.h 
// StackOverflow Example 
// 
// Created by Raphael Caixeta on 8/13/10. 
// Copyright 2010 Raphael Caixeta. All rights reserved. 
// 

#import <UIKit/UIKit.h> 


@interface GRTableView : UITableView <UITableViewDelegate> { 

    UITextField *textField; 

} 

@property(nonatomic, retain) UITextField *textField; 

@end 

// 
// GRTableView.m 
// StackOverflow Example 
// 
// Created by Raphael Caixeta on 8/13/10. 
// Copyright 2010 Raphael Caixeta. All rights reserved. 
// 

#import "GRTableView.h" 

@implementation GRTableView 
@synthesize textField; 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    [textField resignFirstResponder]; 
    [super touchesBegan:touches withEvent:event];  
} 

- (void)dealloc { 
    [super dealloc]; 
} 


@end 

,然後在常規文件在那裏你會分配一個UITableView,僅分配子類的觀點和你的文本字段傳遞給子類。希望有所幫助。

+0

這不是「唯一的做法」。請參閱列表中的其他有效答案。 – 2010-08-20 12:29:32

+0

親自嘗試一下。你會看到點擊UITableView的「背景」將被阻止。如果其他例子有效,你是否真的認爲我會創建一個例子? – 2010-08-20 15:13:13

0

嘗試執行UITextFieldDelegate- (void)textFieldDidEndEditing:(UITextField *)textField方法。

0

這很簡單:創建一個透明的UIView對象,它接收所需區域的觸摸,當觸摸位於該視圖的邊界內時,調用resignFirstResponder。

// somewhere in a view controller 
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; 
[self.view addSubview:backgroundView]; 

// in the touchesBegan:withEvent: method, for example 
UITouch *touch = [[event allTouches] anyObject]; 

if ([field isFirstResponder] && [touch view] == backgroundView) { 
    [field resignFirstResponder]; 
} 

或者,你可以跳過backgroundView的東西,只需添加一個條件語句,就像你的touchesBegan如下:withEvent:方法方法:

UITouch *touch = [[event allTouches] anyObject]; 

if ([field isFirstResponder] && [touch view] != field) { 
    [field resignFirstResponder]; 
} 

如果觸摸! (不)在field的範圍內,那麼你想要刪除鍵盤。

+0

出於某種原因,我的touchesBegan方法沒有被調用。有什麼建議?我的視圖和UITableView具有userInteractionEnabled和multipleTouchEnabled爲YES。 – 2010-08-09 15:28:20

+0

確保touchesBegan:withEvent:方法具有正確的簽名,並且在UIViewController中實現,而不是在視圖本身中實現。 – 2010-08-09 15:36:42

0

您可以隱藏鍵盤在下列情況下,

    • (無效)的tableView:(UITableView的*)的tableView didSelectRowAtIndexPath方法:(NSIndexPath *)indexPath {}
    • (void)TextField:(UITextField *)TxtFld textDidChange:(NSString *)searchText {}

在這兩種情況下,您應該放置[TxtFld resignFirstResponder];而且當你的文本框工作結束時,你正在對該事件執行一些操作,你也應該寫[TxtFld resignFirstResponder];其中TxtFld是UIText字段的對象。

通過使用這個東西,鍵盤將被解僱。您正在編寫的觸摸方法可能無法在UITableviewCell上工作。所以這將是隱藏關鍵板的方式。

它仍然不起作用,然後指定確切的問題發生。

0

有一種比標準的「子類UITableView」或「添加UIView的子類和處理觸摸」更簡單的方法。我在我想處理觸摸的區域上創建一個具有清晰背景色的UIButton。當我將它添加到視圖中時,我將其隱藏屬性設置爲YES。

當文本字段開始編輯時,我將按鈕的隱藏屬性設置爲NO。

然後該按鈕只是響應UITouchUpInside控件事件,在調用[textField resignFirstResponder]和button.hidden = YES的方法中。