很久之前的一个小算法,在这里MARK一下
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
})
}
}
网友评论