我正在构建转换器应用程序。在主屏幕中,我有一个文本字段用于输入数字,在文本字段下方,选择器视图将允许用户选择转换参数(例如kg到g)。
当用户使用以下方法单击背景时,我可以隐藏键盘
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.enterInput resignFirstResponder];
但是当我触摸选择器视图时键盘没有隐藏。
我的问题是当用户触摸选择器视图时如何关闭键盘。
答案 0 :(得分:2)
获得解决方案
1)首先创建一个隐藏的roundRect按钮并将类型更改为自定义(适合选择器的大小)。
2)创建内部动作
- (IBAction)hiddenButtonToHideKeyboard:(id)sender {
[self.enterInput resignFirstResponder];
}
3)创建键盘显示通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onKeyboardAppear:) name:UIKeyboardWillShowNotification object:nil];
4)创建键盘消失通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onKeyboardHide:) name:UIKeyboardWillHideNotification object:nil];
5)键盘出现时按钮可见
-(void)onKeyboardAppear:(NSNotification *)notification
{
hiddenButtonToHideKeyboard.hidden=NO;
}
6)键盘消失时隐藏按钮
-(void)onKeyboardHide:(NSNotification *)notification
{
hiddenButtonToHideKeyboard.hidden=YES;
}
5)完成
我不认为这是一个完美的解决方案,但它对我有用:)
答案 1 :(得分:1)
我在我的代码中使用它。我爬上响应链并重新分配响应者。我把它放在显示pickerView的方法中。到目前为止没有意外的问题如果键盘显示似乎工作,如果没有显示键盘,似乎不会崩溃。
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
答案 2 :(得分:0)
你走了。 UIPickerViews是一个相当复杂的嵌套UIViews系统,这就是为什么你没有从touchesBegan:withEvent:
方法得到任何响应。您可以做的是创建UIPickerView子类,如下所示:
//
// MyPickerView.h
//
#import <UIKit/UIKit.h>
// Protocol Definition that extends UIPickerViewDelegate and adds a method to indicate a touch
@protocol MyPickerViewDelegate <UIPickerViewDelegate>
// This is the method we'll call when we've received a touch. Our view controller should implement it and hide the keyboard
- (void)pickerViewDidReceiveTouch:(UIPickerView *)pickerView;
@end
@interface MyPickerView : UIPickerView
// We're redefining delegate to require conformity to the MyPickerViewDelegate protocol we just made
@property (nonatomic, weak) id <MyPickerViewDelegate>delegate;
@end
//
// MyPickerView.m
//
#import "MyPickerView.h"
@implementation MyPickerView
@synthesize delegate = _myPickerViewDelegate; // We changed the data type of delegate as it was declared in the superclass so it's important to link it to a differently named backing variable
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
// We make sure to call the super method so all standard functionality is preserved
UIView *hitView = [super hitTest:point withEvent:event];
if (hitView) {
// This will be true if the hit was inside of the picker
[_myPickerViewDelegate pickerViewDidReceiveTouch:self];
}
// Return our results, again as part of preserving our superclass functionality
return hitView;
}
@end
然后在ViewController中将其更改为符合<MyPickerViewDelegate>
而不是<UIPickerViewDelegate>
。这是好的,因为MyPickerViewDelegate
继承自UIPickerViewDelegate
并将通过标准UIPickerViewDelegate
方法。
最后在视图控制器中实现pickerViewDidReceiveTouch:
:
- (void)pickerViewDidReceiveTouch:(UIPickerView *)pickerView {
[enterInput resignFirstResponder];
}