背景: 因为我用的 UIPickerView最多只有三个cell,并且还是动态加载的,当只有一个cell的时候UIPickerView的didSelectRow这个选择代理方法就不起作用了,只能在上面放一个Button,但是问题来了,这个Button居然不能接受到点击事件
1.创建一个PickerView
1 2 3 4 5 6 7 8 9 10 11
| - (UIPickerView *)selectPickView{ if (_selectPickView == nil) { _selectPickView = [[UIPickerView alloc]init]; _selectPickView.delegate = self; _selectPickView.dataSource = self; _selectPickView.showsSelectionIndicator = YES; _selectPickView.backgroundColor = [UIColor whiteColor]; _selectPickView.showsSelectionIndicator = YES; } return _selectPickView; }
|
2.并遵守其代理
1 2 3
| @interface JoinConferenceView()<UIPickerViewDelegate,UIPickerViewDataSource>{
}
|
3. 相关代理方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ return 1; }
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{ return 44.0; }
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ return _pickDataArray.count; }
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{ UIButton *button; if (view == nil) { view = [[UIView alloc]init]; view.backgroundColor = [UIColor clearColor]; view.userInteractionEnabled = YES; if (!button) { button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(0, 0, pickerView.bounds.size.width, 44.0); [button setTitle:_pickDataArray[row] forState:UIControlStateNormal]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [button addTarget:self action:@selector(pickButtonAction:) forControlEvents:UIControlEventTouchDown]; button.tag = 1000 + row; [view addSubview:button]; } } return view; } //这里硬是触发不了 - (void)pickButtonAction:(UIButton *)button{ [_selectPickView selectRow:button.tag - 1000 inComponent:0 animated:YES]; _passCodeTextField.text = _pickDataArray[button.tag - 1000]; }
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ _passCodeTextField.text = _pickDataArray[row]; }
|
4.后来用Reveal看了一下UI,原来是PickerView的cell挡住了
5.所以,现在只能用重写 hitTest:
1 2 3 4 5 6 7 8
| //防止PickerView的cell遮挡Button的点击事件 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ id view = [super hitTest:point withEvent:event]; if ([view isKindOfClass:[HWJoinConferenceView class]]) {//防止点击到HWJoinConferenceView,引起无限递归 return nil; } return [view hitTest:[self convertPoint:point toView:view] withEvent:event]; }
|