如果UIScrollView配置了任何标准属性(例如contentInset),我如何获得最小和最大contentOffset?
即。当用户一直向左滚动时,contentOffset将被报告为什么?
即。如果用户一直向下滚动到右下角,那么contentOffset会被报告为什么?
答案 0 :(得分:11)
想象一下,我们有以下UIScrollView:
500 x 500
200 x 200
(10, 10, 20, 20)
计算contentOffsets:
-contentInset.left
(-10)-contentInset.top
(-10)contentSize.width - bounds.width + contentInset.right
(320)contentSize.height - bounds.height + contentInset.bottom
(320)通常,UIScrollView从contentOffset = (0, 0)
开始。但是,当您添加contentInsets时,它会以否定金额开始偏移。当您将第一个位置滚动到视图中以便您不会看到contentInset时,您将会在contentOffset = (0,0)
。
类似的事情发生在最后,而不是300是最大偏移,320变成最大。
func minContentOffset(scrollView: UIScrollView) -> CGPoint {
return CGPoint(
x: -scrollView.contentInset.left,
y: -scrollView.contentInset.top)
}
func maxContentOffset(scrollView: UIScrollView) -> CGPoint {
return CGPoint(
x: scrollView.contentSize.width - scrollView.bounds.width + scrollView.contentInset.right,
y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom)
}
然后,您可以创建一个函数,使用这两个函数来确定滚动视图是否可滚动:
func canVerticallyScroll(scrollView: UIScrollView) -> Bool {
let scrollableHeight = maxContentOffset(scrollView: scrollView).y
- minContentOffset(scrollView: scrollView).y
let viewableHeight = scrollView.bounds.height
return viewableHeight < scrollableHeight
}
或作为扩展名:
extension UIScrollView {
var minContentOffset: CGPoint {
return CGPoint(
x: -contentInset.left,
y: -contentInset.top)
}
var maxContentOffset: CGPoint {
return CGPoint(
x: contentSize.width - bounds.width + contentInset.right,
y: contentSize.height - bounds.height + contentInset.bottom)
}
func scrollToMinContentOffset(animated: Bool) {
setContentOffset(minContentOffset, animated: animated)
}
func scrollToMaxContentOffset(animated: Bool) {
setContentOffset(maxContentOffset, animated: animated)
}
}
答案 1 :(得分:0)
滚动到原点
CGPoint(x: -contentInset.left, y: -contentInset.top)
滚动到底部
CGPoint(x: 0, y: -contentInset.top + contentSize.height - frame.height))
向右滚动
CGPoint(x: 0, y: -contentInset.left + contentSize.width - frame.width))