Swift Tab选项卡滑动,拿去直接用吧!

2021-06-10  本文已影响0人  AlwaysLuckyMa

OC 版本

滑动选项卡!
- (void)tagBtn:(UIButton *)sender {
    CGFloat needScrollowOffsetX = CGRectGetMaxX(sender.frame) - SCREEN_WIDTH / 2;
    if (needScrollowOffsetX < 0) {
        needScrollowOffsetX = 0;
    }
    CGFloat maxScrollowOffsetX = _scrollView.contentSize.width -  _scrollView.width;
    if (needScrollowOffsetX > maxScrollowOffsetX) {
        needScrollowOffsetX = (maxScrollowOffsetX <= 0) ? 0 : maxScrollowOffsetX;
    }
    if (needScrollowOffsetX != _scrollView.contentOffset.x) {
        [_scrollView setContentOffset:CGPointMake(needScrollowOffsetX, 0) animated:NO];
    }
}

Swift 版本

日期滑动
    @objc func selectDateBtn(sender: UIButton) {        
        var needScrollowOffsetX = sender.frame.maxX - SCREEN_WIDTH / 2 - UIAdapter(20)
        if needScrollowOffsetX < 0 {
            needScrollowOffsetX = 0
        }
        let  maxScrollowOffsetX = scrollView!.contentSize.width - scrollView!.frame.width
        if needScrollowOffsetX > maxScrollowOffsetX {
            needScrollowOffsetX = (maxScrollowOffsetX <= 0) ? 0 : maxScrollowOffsetX
        }
        if needScrollowOffsetX != scrollView!.contentOffset.x {
            UIView.animate(withDuration: 0.25, animations: {
                self.scrollView!.contentOffset = CGPoint(x: needScrollowOffsetX, y: 0)
                   }, completion: { (_) in
                    
                   })
        }
    }
func selectLabelCenter() {
//计算选中label的centerX
        let centerX = CGFloat(self.segmentControl.selectedSegmentIndex)*itemWidth + itemWidth/2
//计算出应该偏移的offsetX
        var needScrollowOffsetX = centerX - slidingView.width/2
//最小值不能小于0
        if needScrollowOffsetX < 0{
            needScrollowOffsetX = 0
        }
//不能大于最大值(滑动至最右侧)
        let maxScrollowOffsetX = slidingView.contentSize.width-slidingView.width
        if needScrollowOffsetX > maxScrollowOffsetX {
            needScrollowOffsetX = maxScrollowOffsetX
        }
//不需要滑动时不用滑动
        if needScrollowOffsetX != slidingView.contentOffset.x {
            slidingView.isUserInteractionEnabled = false
            UIView.animate(withDuration: 1.0, animations: {
                self.slidingView.contentOffset = CGPoint(x: needScrollowOffsetX, y: 0)
            }, completion: { (_) in
                self.slidingView.isUserInteractionEnabled = true
            })
        }
    }

记得给个赞呦!

上一篇下一篇

猜你喜欢

热点阅读