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

标签 ios uisegmentedcontrol uiswipegesturerecognizer

如何通过手势改变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];
        }
    }

最佳答案

您需要先检查新索引是否有效。如果您已经在第一个选项卡上,则无法向左移动;如果您在最后一个选项卡上,则无法向右移动。所以在设置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];
}

关于ios - 如何通过滑动手势改变分段控件的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16856819/

相关文章:

php - 如何保存推送通知的设备 ID - iOS

ios - 我使用 UIView `animateWithDuration:animations:` 方法为我的 View 设置动画,它的底部不断变化,但它显示没有设置动画

ios - 如何仅针对 UITabbarController 禁用 UI 导航向上滑动手势?

ios - Swift 中的滑动页面转换

ios - UIView 滑动手势改变图像

ios - 委托(delegate)函数不调用

iOS 如何确定 UILabel 是否更改了它的文本

ios - 使用分段控件返回 cellForRowAtIndexPath 中的两个单元格

ios - 在分段控件之间切换时隐藏线条

uisearchbar - 防止 UISearchDisplayController 隐藏导航栏