添加按钮以隐藏键盘

时间:2011-05-30 18:20:11

标签: ios cocoa-touch keyboard uitextview

在UITextView上隐藏键盘,有方法:

...
    textfield.returnKeyType = UIReturnKeyDone;
    textfield.delegate = self;
....

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;

}

但是如果我想将“完成”按钮留给“返回”并添加按钮来隐藏键盘,我该怎么办?

3 个答案:

答案 0 :(得分:38)

您可以指定一个工具栏,其中包含一个取消键盘的按钮,作为文本字段的inputAccessoryView。一个简单的例子就是,

UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:textField action:@selector(resignFirstResponder)] autorelease];
UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)] autorelease];
toolbar.items = [NSArray arrayWithObject:barButton];

textField.inputAccessoryView = toolbar;

答案 1 :(得分:5)

Swift 2.0版本:

//Declared at top of view controller
var accessoryDoneButton: UIBarButtonItem!
let accessoryToolBar = UIToolbar(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.width, 44))
//Could also be an IBOutlet, I just happened to have it like this
let codeInput = UITextField()

//Configured in viewDidLoad()
self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(self.donePressed(_:)))
self.accessoryToolBar.items = [self.accessoryDoneButton]
self.codeInput.inputAccessoryView = self.accessoryToolBar
斯威夫特4:

//Declared at top of view controller
var accessoryDoneButton: UIBarButtonItem!
let accessoryToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
//Could also be an IBOutlet, I just happened to have it like this
let codeInput = UITextField()

//Configured in viewDidLoad()
self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.donePressed))
self.accessoryToolBar.items = [self.accessoryDoneButton]
self.codeInput.inputAccessoryView = self.accessoryToolBar

func donePressed() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

UIToolBar Documentation

'inputAccessoryView' documentation

答案 2 :(得分:3)

这可以更轻松地完成!

我在IB中创建了一个自定义视图,在我的viewController.h中,我刚刚创建了一个IBOutlet UIView *accessoryView;,并将它们连接起来- (IBAction)dismissKeyboard;

我在视图中放入一个带有完成按钮的工具栏,与IBAction建立连接并写道: [textView resignFirstResponder]

- (void)viewDidLoad
{
    textView.inputAccessoryView = accessoryView;
    [super viewDidLoad];
}

但实际上看起来有点奇怪而且非苹果风格......有个主意吗?