美文网首页
点击按钮的时候切换不同的view

点击按钮的时候切换不同的view

作者: 陈水寒 | 来源:发表于2017-01-20 09:49 被阅读56次

点击按钮的时候切换不同的view

思路:scrollView的contentSize大小为5个屏幕宽,每个屏幕宽度可以添加1个view,当用户点击不同的按钮的时候,算出对应scrollview的偏移量就可以显示不同的view,步骤如下:

  1. 当点击按钮的时候,取出当前按钮的索引号
  2. 根据按钮的索引号,计算出scrollview的偏移量
  3. 设置scrollview的偏移量
     NSUInteger index = [self.titlesView.subviews indexOfObject:titleBtn]; // 取出当前按钮的索引,按钮的索引顺序刚好是(0,1,2,3,4)
    [UIView animateWithDuration:0.3 animations:^{
        // 点击按钮的时候移动下划线
        self.titleUnderline.gg_width = titleBtn.titleLabel.gg_width + 10; // 设置下划线的宽度等于按钮文字的宽度,一定要先设置宽度,再设置中心位置
        self.titleUnderline.gg_centerX = titleBtn.gg_centerX;
        
        //点击按钮的时候移动scrollview
        CGFloat offsetX = self.scrollView.gg_width * index; // 算出每个view的偏移量
        self.scrollView.contentOffset = CGPointMake(offsetX, self.scrollView.contentOffset.y);
    } completion:^(BOOL finished) {
        CGFloat scrollViewW = self.scrollView.gg_width;
        CGFloat scrollViewH = self.scrollView.gg_height;
    
        // 取出子控制器的view
        UIView *childView = self.childViewControllers[index].view;
        childView.backgroundColor = GGRandomColor;
        childView.frame = CGRectMake(index * scrollViewW, 0, scrollViewW, scrollViewH);
        [self.scrollView addSubview:childView];
    }];

拖拽scrollview结束的时候对应按钮被选中

思路:scrollview拖拽结束的时候scrollview已经产生偏移量,根据偏移量计算出当前的索引,设置控制器成为scrollview的代理,在拖拽结束的方法中重新调用按钮点击的方法即可

// 拖拽接收后scrollview静止后调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSUInteger index = self.scrollView.contentOffset.x / self.scrollView.gg_width;
    GGTitleBtn *titleBtn = self.titlesView.subviews[index];
    [self titleBtnClk:titleBtn];
}

效果如下:

演示效果.gif

相关文章

网友评论

      本文标题:点击按钮的时候切换不同的view

      本文链接:https://www.haomeiwen.com/subject/qiswbttx.html