如何通过swipegesture改变分段控制的价值?

时间:2013-05-31 12:02:29

标签: ios uisegmentedcontrol uiswipegesturerecognizer

如何通过swipegesture更改segmentedcontrol的值?

“无效参数不满足: 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];
        }
    }

1 个答案:

答案 0 :(得分: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];
}