3

這裏有一些答案,例如this,但在存在UIScrollViewUICollectionView的情況下,它不起作用。
viewController上的touchesBegan方法永遠不會被調用。當視圖包含UICollectionView時,隱藏UITextField外部任何位置的鍵盤UICollectionView

在屏幕上,我有一個UITextField頂部。
在此之下,填滿屏幕的其餘部分是UICollectionView
我需要取消鍵盤,如果我碰任何地方除了UITextField包括收集觀點顯然

那麼,什麼是做到這一點的最好方法是什麼?

對於這樣一個共同的UI樣式好像應該有一個衆所周知的解決方案,但我還沒有遇到過。

+0

你試過[TPKeyboardAvoiding(https://github.com/michaeltyson/TPKeyboardAvoiding)? – staticVoidMan

回答

4

要關閉鍵盤上的查看的水龍頭:點擊手勢添加到您的ViewController.collectionView如下:

//declare a property to store your current responder 
@property (nonatomic, assign) id currentResponder; 
//in viewDidLoad: 

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignOnTap:)]; 
    [singleTap setNumberOfTapsRequired:1]; 
    [singleTap setNumberOfTouchesRequired:1]; 
    [self.collectionView addGestureRecognizer:singleTap]; 


//Implement the below delegate method: 

- (void)textFieldDidBeginEditing:(UITextField *)textField { 
    self.currentResponder = textField; 
} 

//Implement resignOnTap: 

- (void)resignOnTap:(id)sender { 
    [self.currentResponder resignFirstResponder]; 
} 
+0

這將工作,如果用戶點擊收集視圖,但我希望有一個更通用的解決方案,爲鍵盤外的任何觸摸。 – soleil

+0

我不認爲有任何其他簡單的方法。任何你必須在這裏實現手勢識別。讓我知道如果我的答案是有用的.. :) –

1

最簡單的方法來做到這一點是:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    [self.view endEditing:YES]; 
} 
0

這裏有一個更好的該解決方案不需要將手勢識別器單獨添加到一切。它在Swift中,但可以很容易地轉換爲ObjC。

以下內容添加到您的viewDidLoad中():

let tap = UITapGestureRecognizer(target: self, action: "dismissKeyboard") 
tap.cancelsTouchesInView = false 
view.addGestureRecognizer(tap) 

,然後添加下面的方法聲明:

func dismissKeyboard() 
{ 
    view.endEditing(true) 
} 

...其中view是你的文本字段。

相關問題