iPhone UIScrollView Speed Check

后端 未结 8 1643
梦如初夏
梦如初夏 2020-11-30 19:31

I know how to get the contentOffset on movement for a UIScrollView, can someone explain to me how I can get an actual number that represents the current speed of a UIScrollV

8条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 20:07

    2017...

    It's very easy to do this with modern Swift/iOS:

    var previousScrollMoment: Date = Date()
    var previousScrollX: CGFloat = 0
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
            
        let d = Date()
        let x = scrollView.contentOffset.x
        let elapsed = Date().timeIntervalSince(previousScrollMoment)
        let distance = (x - previousScrollX)
        let velocity = (elapsed == 0) ? 0 : fabs(distance / CGFloat(elapsed))
        previousScrollMoment = d
        previousScrollX = x
        print("vel \(velocity)")
    

    Of course you want the velocity in points per second, which is what that is.

    Humans drag at say 200 - 400 pps (on 2017 devices).

    1000 - 3000 is a fast throw.

    As it slows down to a stop, 20 - 30 is common.

    So very often you will see code like this ..

        if velocity > 300 {
        
            // the display is >skimming<
            some_global_doNotMakeDatabaseCalls = true
            some_global_doNotRenderDiagrams = true
        }
        else {
        
            // we are not skimming, ok to do calculations
            some_global_doNotMakeDatabaseCalls = false
            some_global_doNotRenderDiagrams = false
        }
    

    This is the basis for "skimming engineering" on mobiles. (Which is a large and difficult topic.)

    Note that that is not a complete skimming solution; you also have to care for unusual cases like "it has stopped" "the screen just closed" etc etc.

提交回复
热议问题