1

如何通过滑动手势更改分段控件的值?

“无效参数不满足:selectedSegmentIndex < (NSInteger)self._items.count”

    - (void)updateSelectedSegmentText 
    {
        int theSegmentIndex = [_segmentedControl selectedSegmentIndex];
        NSDictionary *theInfo = [self.top.segments objectAtIndex:theSegmentIndex];
        self.bioTextView.text = [NSString stringWithFormat:@"%@", theInfo [@"sData"]];
        [self.bioTextView scrollRangeToVisible:NSMakeRange(0, 0)];
    }

    - (void)swipe:(UISwipeGestureRecognizer *)swipeRecogniser
    {
        s = 1;
        if ([swipeRecogniser direction] == UISwipeGestureRecognizerDirectionLeft)
        {
            self.segmentedControl.selectedSegmentIndex -=s;
            [self updateSelectedSegmentText];
        }
        else if ([swipeRecogniser direction] == UISwipeGestureRecognizerDirectionRight)
        {
            self.segmentedControl.selectedSegmentIndex +=s;
            [self updateSelectedSegmentText];
        }
    }
4

1 回答 1

2

您需要首先检查新索引是否有效。如果您已经在第一个选项卡上,则无法向左移动;如果您在最后一个选项卡上,则无法向右移动。因此,您需要先计算新索引,然后在设置 selectedSegmentIndex 属性之前检查它是否在范围内:

NSInteger index = self.segmentedControl.selectedSegmentIndex;
if ([swipeRecogniser direction] == UISwipeGestureRecognizerDirectionLeft) {
    --index;
} else if ([swipeRecogniser direction] == UISwipeGestureRecognizerDirectionRight) {
    ++index;
}

if (0 <= index && index < self.segmentedControl.numberOfSegments) {
    self.segmentedControl.selectedSegmentIndex = index;
    [self updateSelectedSegmentText];
}
于 2013-05-31T12:15:32.037 回答