Search
 
SCRIPT & CODE EXAMPLE
 

SWIFT

how to add dragdown gesture recognizer on view

class ViewConrtoller: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(onDrage(_:))))
    }

    @objc func onDrage(_ sender:UIPanGestureRecognizer) {
        let percentThreshold:CGFloat = 0.3
        let translation = sender.translation(in: view)
    
        let newX = ensureRange(value: view.frame.minX + translation.x, minimum: 0, maximum: view.frame.maxX)
        let progress = progressAlongAxis(newX, view.bounds.width)
    
        view.frame.origin.x = newX //Move view to new position
    
        if sender.state == .ended {
            let velocity = sender.velocity(in: view)
           if velocity.x >= 300 || progress > percentThreshold {
               self.dismiss(animated: true) //Perform dismiss
           } else {
               UIView.animate(withDuration: 0.2, animations: {
                   self.view.frame.origin.x = 0 // Revert animation
               })
          }
       }
    
       sender.setTranslation(.zero, in: view)
    }
}

func progressAlongAxis(_ pointOnAxis: CGFloat, _ axisLength: CGFloat) -> CGFloat {
        let movementOnAxis = pointOnAxis / axisLength
        let positiveMovementOnAxis = fmaxf(Float(movementOnAxis), 0.0)
        let positiveMovementOnAxisPercent = fminf(positiveMovementOnAxis, 1.0)
        return CGFloat(positiveMovementOnAxisPercent)
    }
    
    func ensureRange<T>(value: T, minimum: T, maximum: T) -> T where T : Comparable {
        return min(max(value, minimum), maximum)
    }
Comment

PREVIOUS NEXT
Code Example
Swift :: swift session.input 
Swift :: Swift Double 
Swift :: Swift Closure as function parameter 
Swift :: Swift If-statement 
Swift :: declaration of array in swift by two methods. 
Swift :: Swift guard Vs if Statement 
Swift :: Swift continue with while loop 
Swift :: Swift for Loop inside a while Loop 
Swift :: Swift Array With Mixed Data Types 
Swift :: async await apis for ios 13 
Swift :: Swift Access Class Property using Objects 
Swift :: swift UI color rgb 
Swift :: UISearchController keys 
Swift :: how to call another view controller method when button click from another ios swift 
Swift :: Swift Things to Remember About Swift Range 
Swift :: Swift Labeled Statement with break 
Swift :: ns transport swift code 
Swift :: Swift Hashable Protocol 
Swift :: Swift Function Overloading 
Swift :: spilit string in swift 
Swift :: sum in array swift 
Ruby :: ruby file extension 
Ruby :: ruby calculate execution time 
Ruby :: fibonacci sums ruby 
Ruby :: ruby/rails file get line number 
Ruby :: how to get current month end date in ruby 
Ruby :: rails order 
Ruby :: ruby write csv file 
Ruby :: ruby datetime parse 
Ruby :: ruby copy file 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =