我有一个文本字段显示在UITableViewCell中,我希望能够在用户触摸文本字段以外的任何屏幕区域时隐藏键盘。我知道可以使用[field resignFirstResponder];,但我不知道如何拦截UITableView背景上的触摸事件,以便调用"resignFirstResponder"。
非常感谢您的帮助。
非常感谢您的帮助。
// 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,只需要分配子类视图并将您的文本字段传递给子类即可。希望这能有所帮助。
// 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];
}
UITextFieldDelegate
的- (void)textFieldDidEndEditing:(UITextField *)textField
方法。您可以在以下情况下隐藏键盘:
在这两种情况下,您应该放置[TxtFld resignFirstResponder];并且当您的文本字段工作完成时,您也应该编写[TxtFld resignFirstResponder];其中TxtFld是UIText字段的对象。
通过使用此方法,键盘将被解除。您编写的触摸方法可能无法在UITableviewCell上工作。因此,这将是隐藏键盘的方法。
如果仍然无法正常工作,请指定出现的确切问题。
有一种比标准的“子类化UITableView”或“添加UIView子类并处理触摸”的方法更容易。我创建了一个透明背景颜色的UIButton,覆盖在我想要处理触摸的区域上。当我将其添加到视图中时,我将其hidden属性设置为YES。
当文本字段开始编辑时,我将按钮的hidden属性设置为NO。
然后,该按钮仅响应UITouchUpInside控件事件,在调用[textField resignFirstResponder]和button.hidden = YES的方法中。