Swift 项目在屏幕上移动的百分比

Swift Percent Item Moved Across Screen

问题:

您正在尝试获取 0 到 1 之间的数字,具体取决于滚动视图中的视图在可见屏幕上移动了多少。

条件:

尝试:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    guard let firstScrollviewView = items.first else {return}
    let screenWidth = UIScreen.main.bounds.width

    // This should return a value between 0 and 1
    let xOffset = firstScrollviewView.convert(CGPoint(x: firstScrollviewView.frame.minX, y: 0), to: view).x
    var percentViewMovedOnVisibleScreen: CGFloat = xOffset / screenWidth

    let minValue: CGFloat = 0
    let maxValue: CGFloat = 1
    percentViewMovedOnVisibleScreen = max(min(percentViewMovedOnVisibleScreen, maxValue), minValue)

    // RETURN value between 0 and 1 - NOT CORRECT
    print("HERE x: ", percentViewMovedOnVisibleScreen)
}

这非常接近,但我认为 xOffset 属性 不正确。

GitHub: https://github.com/Alexander-Frost/ViewContentOffset

xOffset 需要更改为:

let xOffset = scrollView.convert(CGPoint(x:firstScrollviewView.frame.minX, y: 0), to: view).x