我假设您说的是UITextField 而不是UITextView,因为您的问题不是很清楚吗?如果是这样,请确保您的类在接口文件中标记为UITextFieldDelegate,
@interface MyController: UIViewController <UITextFieldDelegate> {
UITextField *activeTextField;
// ...remainder of code not show ...
}
然后你应该实现下面的两个委托方法,
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
activeTextField = textField;!
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
activeTextField = nil;
[textField resignFirstResponder];
return YES;
}
但是,如果您使用的是UITextView,那么事情会稍微复杂一些。 UITextViewDelegate 协议缺少与textFieldShouldReturn: 方法等效的方法,大概是因为我们不应该期望 Return 键是用户希望停止在多行文本输入对话框中编辑文本的信号(毕竟,用户可能希望通过按 Return 来插入换行符)。
但是,有几种方法可以解决 UITextView 无法使用键盘辞去第一响应者的职务。通常的方法是当UITextView 出现弹出式键盘时,在导航栏中放置一个完成 按钮。当点击此按钮时,该按钮会要求文本视图辞去第一响应者的身份,然后将关闭键盘。
但是,根据您设计界面的方式,您可能希望UITextView 在用户在UITextView 本身之外点击时退出。为此,您需要继承 UIView 以接受触摸,然后指示文本视图在用户在视图本身之外点击时退出。
创建一个新类,
#import <UIKit/UIKit.h>
@interface CustomView : UIView {
IBOutlet UITextView *textView;
}
@end
然后,在实现中,实现touchesEnded:withEvent: 方法并要求UITextView 辞去第一响应者的职务。
#import "CustomView.h"
@implementation CustomView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void) awakeFromNib {
self.multipleTouchEnabled = YES;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"touches began count %d, %@", [touches count], touches);
[textView resignFirstResponder];
[self.nextResponder touchesEnded:touches withEvent:event];
}
@end
添加类后,您需要保存所有更改,然后进入 Interface Builder 并单击您的视图。在 Utility 选项卡中打开身份检查器并将 nib 文件中的视图类型更改为 CustomView 而不是默认的 UIView 类。然后在 Connections Inspector 中,将textView 出口拖到UITextView。这样做之后,一旦你重建你的应用程序,在活动 UI 元素之外的触摸现在将关闭键盘。但是请注意,如果您要子类化的UIView 位于其他 UI 元素的“后面”,则这些元素将在触摸到达 UIView 层之前拦截它们。因此,虽然这个解决方案很优雅,但它只能在某些情况下使用。在许多情况下,您必须求助于在导航栏中添加 完成 按钮以关闭键盘的蛮力方法。