无图无真相!
![](https://img.haomeiwen.com/i5468551/6bf738d89b944120.gif)
思路:3 个 view,1 个scrollView 滚动区域是三个view的大小,默认显示中间那个 contentOffset(w, 0)
向左滚动时,刚好到第三个时,修改数据源为下一个,重新offset到中间
向右滚动时, 刚好到第一个时,修改数据源为上一个,重新offset到中间
代码如下:
class XXVC: UIViewController {
lazy var hScroll: UIScrollView = {
let v = UIScrollView()
v.isPagingEnabled = true
return v
}()
lazy var v1: UIView = {
let v = UIView()
v.backgroundColor = .red
return v
}()
lazy var v2: UIView = {
let v = UIView()
v.backgroundColor = .green
return v
}()
lazy var v3: UIView = {
let v = UIView()
v.backgroundColor = .blue
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
testScroll()
}
//测试无线滚动
func testScroll() {
view.addSubview(hScroll)
hScroll.addSubview(v1)
hScroll.addSubview(v2)
hScroll.addSubview(v3)
hScroll.frame = CGRect(x: 0, y: 100, width: AppConst.width_screen, height: 200)
v1.frame = CGRect(x: 0, y: 0, width: AppConst.width_screen, height: 200)
v2.frame = CGRect(x: AppConst.width_screen, y: 0, width: AppConst.width_screen, height: 200)
v3.frame = CGRect(x: AppConst.width_screen*2, y: 0, width: AppConst.width_screen, height: 200)
hScroll.contentSize = CGSize(width: AppConst.width_screen*3, height: 200)
hScroll.contentOffset = CGPoint(x: AppConst.width_screen, y: 0)
hScroll.delegate = self
hScroll.showsVerticalScrollIndicator = false
hScroll.showsHorizontalScrollIndicator = false
}
}
extension XXVC: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = hScroll.contentOffset.x
debugPrint("---- offsetX = \(offsetX)")
if offsetX == 0 {
debugPrint("向右滑动 = 上一个")
//将中间的数据修改为左边的 ,并且偏移到中间
let c = v1.backgroundColor
v1.backgroundColor = v3.backgroundColor
v3.backgroundColor = v2.backgroundColor
v2.backgroundColor = c
hScroll.contentOffset = CGPoint(x: AppConst.width_screen, y: 0)
} else if offsetX == AppConst.width_screen*2 {
debugPrint("向左滑动 - 下一个")
//将中间的数据更改为右边的, 并且偏移到中间
let c = v3.backgroundColor
v3.backgroundColor = v1.backgroundColor
v1.backgroundColor = v2.backgroundColor
v2.backgroundColor = c
hScroll.contentOffset = CGPoint(x: AppConst.width_screen, y: 0)
}
}
}
存在问题:滑动比较快的时候容易顶左右两边无法滑动
解决思路:扩大滚动区域,contentSize 设置为5个view宽度
确实可以解决!
以上代码仅供参考,请自行修改。
网友评论