UIPicker detect tap on currently selected row

后端 未结 8 1380
礼貌的吻别
礼貌的吻别 2020-12-01 10:11

I have a UIPickerView and The method didSelectRow is not called when tapping on a selected row. I need to handle

相关标签:
8条回答
  • 2020-12-01 11:04

    First, conform the class to the UIGestureRecognizerDelegate protocol

    Then, in the view setup:

    UITapGestureRecognizer *tapToSelect = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                                     action:@selector(tappedToSelectRow:)];
    tapToSelect.delegate = self;
    [self.pickerView addGestureRecognizer:tapToSelect];
    

    And elsewhere:

    #pragma mark - Actions
    
    - (IBAction)tappedToSelectRow:(UITapGestureRecognizer *)tapRecognizer
    {
        if (tapRecognizer.state == UIGestureRecognizerStateEnded) {
            CGFloat rowHeight = [self.pickerView rowSizeForComponent:0].height;
            CGRect selectedRowFrame = CGRectInset(self.pickerView.bounds, 0.0, (CGRectGetHeight(self.pickerView.frame) - rowHeight) / 2.0 );
            BOOL userTappedOnSelectedRow = (CGRectContainsPoint(selectedRowFrame, [tapRecognizer locationInView:self.pickerView]));
            if (userTappedOnSelectedRow) {
                NSInteger selectedRow = [self.pickerView selectedRowInComponent:0];
                [self pickerView:self.pickerView didSelectRow:selectedRow inComponent:0];
            }
        }
    }
    
    #pragma mark - UIGestureRecognizerDelegate
    
    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    {
        return true;
    }
    
    0 讨论(0)
  • 2020-12-01 11:05
    1. Add a tapGestureRecognizer to the pickerView as already suggested

    2. Provide views for the picker rows, not the title, via

      -(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

    3. In the gesture's callback method do this

    -(void)pickerTapped:(UIGestureRecognizer *)gestureRecognizer {

    UIPickerView * pv = (id)gestureRecognizer.view;
    UIView * selView = [pv viewForRow:[pv selectedRowInComponent:0]
                         forComponent:0];
    CGPoint touchPoint = [gestureRecognizer locationInView:selView];
    BOOL tapOnSelection = CGRectContainsPoint(selView.bounds, touchPoint);
    
    if (tapOnSelection) ...
    

    }

    I think is more elegant then doing pixel math

    0 讨论(0)
提交回复
热议问题