干得好。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];
}