【问题标题】:Custom paging for UIScrollViewUIScrollView 的自定义分页
【发布时间】:2017-05-20 16:22:49
【问题描述】:

我有一个 UIScrollView 可以水平滚动并启用分页。有没有办法改变滚动视图的分页,使其在滚动视图的整个长度中捕捉到一半。我添加了显示我正在寻找的图片。

override func viewDidLoad() {
    super.viewDidLoad()


let scrollView = UIScrollView()
scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
scrollView.contentSize = CGSize(width: self.view.frame.size.width * 2, height: self.view.frame.size.height)
scrollView.isPagingEnabled = true
self.view.addSubview(scrollView)

let view1 = UIView()
view1.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width / 2, height: self.view.frame.size.height)
view1.backgroundColor = UIColor.purple
scrollView.addSubview(view1)

let view2 = UIView()
view2.frame = CGRect(x: self.view.frame.size.width / 2, y: 0, width: self.view.frame.size.width / 2, height: self.view.frame.size.height)
view2.backgroundColor = UIColor.green
scrollView.addSubview(view2)

let view3 = UIView()
view3.frame = CGRect(x: self.view.frame.size.width, y: 0, width: self.view.frame.size.width / 2, height: self.view.frame.size.height)
view3.backgroundColor = UIColor.yellow
scrollView.addSubview(view3)

let view4 = UIView()
view4.frame = CGRect(x: self.view.frame.size.width + self.view.frame.size.width / 2, y: 0, width: self.view.frame.size.width / 2, height: self.view.frame.size.height)
view4.backgroundColor = UIColor.red
scrollView.addSubview(view4)

}

【问题讨论】:

  • 请详细说明并展示您的代码
  • 我有一个覆盖整个屏幕的滚动视图和滚动视图内部的四个视图。这四个子视图中的每一个都具有屏幕宽度的一半。我希望这个滚动视图能够捕捉到下一个子视图(它是屏幕宽度的一半)。我将附上一段视频以及我的代码,以展示我已经构建的内容。

标签: ios iphone swift swift3


【解决方案1】:

您可以为滚动视图设置委托并实现UIScrollViewDelegate 方法之一:

func scrollViewWillEndDragging(
    _ scrollView: UIScrollView,
    withVelocity velocity: CGPoint,
    targetContentOffset: UnsafeMutablePointer<CGPoint>
)

当您收到此呼叫时,您需要执行一些自定义逻辑。具体来说,您将检查targetContentOffsetvelocity 以分别查看scrollView 预计停止的位置以及用户拖动的方向。然后将targetContentOffset 更改为它应该实际停止的新位置。

在您的情况下,新的targetContentOffsetx-值将是偶数页的倍数。显然,如果您有奇数页,则必须考虑最后一页的偏移量并做一些不同的事情。

您可能还需要禁用默认的UIScrollView 分页并自己处理所有分页,因为您的自定义行为与默认分页行为冲突。

【讨论】:

  • 谢谢!我试试这个
猜你喜欢
  • 2011-10-12
  • 1970-01-01
  • 2012-03-11
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多