UISegmentedControl register taps on selected segment

后端 未结 20 3081
渐次进展
渐次进展 2020-12-04 15:28

I have a segmented control where the user can select how to order a list. Works fine.

However, I would like that when an already selected segment is tapped, the orde

20条回答
  •  囚心锁ツ
    2020-12-04 15:52

    Seems like a fun question to answer. This scheme expands upon Steve E's and yershuachu's solutions. This version uses a UITapGestureRecognizer to capture all touches and which sets the selectedSegmentIndex to -1; but it also passes on all touches to the UISegmentedControl so it can handle any normal touches. No subclassing is required.

    UISegmentedControl *mySegControl;
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        [mySegControl addTarget:self action:@selector(segmentAction:)
               forControlEvents:UIControlEventValueChanged];
        // allow the a seg button tap to be seen even if already selected
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]
                                              initWithTarget:self action:@selector(unitsSegTap:)];
        tapGesture.cancelsTouchesInView = NO; // pass touches through for normal taps
        [mySegControl addGestureRecognizer:tapGesture];
    
        // continue setup ...
    }
    
    - (void)segTap:(UITapGestureRecognizer *)sender
    {
        mySegControl.selectedSegmentIndex = -1;
    }
    
    // called for UIControlEventValueChanged
    - (void)segmentAction:(UISegmentedControl *)sender
    {
        NSInteger index = sender.selectedSegmentIndex;
        NSLog(@"unitsSegmentAction %d",(int)index);
        // process the segment
    }
    

提交回复
热议问题