Search code examples
iosuipickerview

How to add UIButton with UIPickerView cell?


I have a custom UIPickView ,in (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view custom UIButton clicked,but not working,what should I do? Please help us. Thanks

My code:

  - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
        UIButton *button;
        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:UIControlEventTouchUpInside];
            button.tag = 1000 + row;
        }
        return button;
    }

    - (void)pickButtonAction:(UIButton *)button{
        NSLog(@"button.tag = %ld",(long)button.tag);
    }

NO need this code

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ }

updata code:

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{
    NSLog(@"button.tag = %ld",(long)button.tag);//always not executed
}

Solution

  • OK,I see, Button click event block with UIPickTableViewWrapperCell

    enter image description here

    My code:

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
        id view = [super hitTest:point withEvent:event];
        if ([view isKindOfClass:[UIView class]]) {
            return nil;
        }
        return [view hitTest:[self convertPoint:point toView:view] withEvent:event];
    }