resignFirstResponder when tapping UITableView?

匆匆过客 提交于 2019-12-23 22:41:45

问题


I have a UITableView with two custom cells and each of them has a subview with a UITextField inside it. I have tried adding a UIButton on top of the UITableView and have it resignFirstResponder but that just means you won't be able to tap anywhere else - not even on the UITextFields to enter text.

How do I make it so if I tap outside those two UITextFields, I can call resignFirstResponder, so the user can get back to the other cells?

Thanks


回答1:


I asked a similar question and found an answer myself which I posted. Basically you can override hitTest:withEvent: in your custom UITableViewCell which lets you detect when a touch occurred in your cell or any other cell that is in the table view. I provided an example hitTest: method that duplicates the functionality of the original hitTest: and you can just add what you need to it. You can add your resignFirstResponder inside the hitTest function like I did or customize it further.




回答2:


A nice simple way to do it would be to subclass a UITableView and implement the touch methods (not forgetting to pass them to the super afterwards!). From in there you can inspect a touch in touches began and decide whether it's a touch that's inside the UITextField (using the hitTest: method in UIView). If the hitTest does not return a UITextField you can call a method in your controller to resign the first responder. Hope this points you in the right direction!




回答3:


Instead of trying to tap outside of the field to resign first responder, just resize your tableview with -setFrame when the keyboard displays so that it is in the visible area above the keyboard. Then you'll be able to scroll the view to the other cells. You can be notified that the keyboard is visible by registering for the event like this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

Then implement keyboardWillShow:

- (void)keyboardWillShow:(NSNotification*)notification;
{
    [tableView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 200.0f)];
}

Best Regards.



来源:https://stackoverflow.com/questions/1591738/resignfirstresponder-when-tapping-uitableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!