如何在iitableviewcell中将textfield作为第一响应者

时间:2011-11-23 20:13:58

标签: iphone objective-c cocoa-touch uitableview uitextfield

使用标准UITextField时,我使用此代码将我的firstResponder辞职为UIView

但我现在UITextField中的UITableViewCell UITableView - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; if ([self.temperatureTextField isFirstResponder] && [touch view] != self.temperatureTextField) { [self.temperatureTextField resignFirstResponder]; } [super touchesBegan:touches withEvent:event]; } ,当我点击textField外部时,代码不会将文本字段作为第一响应者重新签名。任何想法如何使这项工作?

{{1}}

enter image description here

2 个答案:

答案 0 :(得分:14)

[[self tableView] endEditing:YES];是我的标准方法。

答案 1 :(得分:1)

为了补充Matt Wilding对UITableView特定案例的回答,我使用的方法如下: 我们通常想要的基本上是在两种情况下隐藏键盘:点击文本UI元素外部,或向下/向上滚动UITableView。我们可以通过TapGestureRecognizer轻松添加第一个场景,第二个场景通过UIScrollViewDelegate scrollViewWillBeginDragging:方法添加。 第一项业务,隐藏键盘的方法:

   /**
     *  Shortcut for resigning all responders and pull-back the keyboard
     */
    -(void)hideKeyboard
    {
        //this convenience method on UITableView sends a nested message to all subviews, and they resign responders if they have hold of the keyboard
        [self.tableView endEditing:YES];

    }

此方法会在UITableView视图层次结构中重新分配子视图的任何textField UI,因此它比独立地重新分配每个元素更实用。

接下来,我们通过外部点击手势解决问题:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupKeyboardDismissGestures];

}

- (void)setupKeyboardDismissGestures
{

//    Example for a swipe gesture recognizer. it was not set-up since we use scrollViewDelegate for dissmin-on-swiping, but it could be useful to keep in mind for views that do not inherit from UIScrollView
//    UISwipeGestureRecognizer *swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
//    swipeUpGestureRecognizer.cancelsTouchesInView = NO;
//    swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
//    [self.tableView addGestureRecognizer:swipeUpGestureRecognizer];

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    //this prevents the gestureRecognizer to override other Taps, such as Cell Selection
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tapGestureRecognizer];

}

将tapGestureRecognizer.cancelsTouchesInView设置为NO是为了避免gestureRecognizer覆盖UITableView的正常内部工作(例如,不干扰单元格选择)。

最后,要处理在向上/向下滚动UITableView时隐藏键盘,我们必须实现UIScrollViewDelegate协议scrollViewWillBeginDragging:方法,如下:

.h文件

@interface MyViewController : UIViewController <UIScrollViewDelegate>

.m文件

#pragma mark - UIScrollViewDelegate

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hideKeyboard];
}

我希望它有所帮助! =)