使用计时器旋转UIPickerView组件

问题描述

我想使用计时器快速旋转所有UIPickerView组件,例如彩票轮。我在UIPickerView中有3个组件,希望同时旋转所有组件。我正在下面的代码中旋转UIPickerView中的组件:

let timer = Timer.scheduledTimer(timeInterval: 2.0,target: self,selector: #selector(scrollRandomly),userInfo: nil,repeats: true);

@objc func scrollRandomly() {

    let row:Int = Int(arc4random() % 9);
    let row1:Int = Int(arc4random() % 9);
    let row2:Int = Int(arc4random() % 9);

    pickerView.selectRow(row,inComponent: 0,animated: true)
    pickerView.selectRow(row1,inComponent: 1,animated: true)
    pickerView.selectRow(row2,inComponent: 2,animated: true)


}

谢谢, 鲁沙卜

解决方法

我使用此扩展名

self.view.beginRotating()
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
    self.view.stopRotating()
}

_

fileprivate var RotatingObjectHandle: UInt8 = 0
fileprivate var RotationCycleHandler: UInt8 = 0


extension UIView {
    
    private var shouldStopRotating: Bool {
        
        get {
            
            return objc_getAssociatedObject(self,&RotationCycleHandler) as? Bool ?? false
        }
        set {
            
            objc_setAssociatedObject(self,&RotationCycleHandler,newValue,.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private(set) var isRotating: Bool {
        
        get {
            
            return objc_getAssociatedObject(self,&RotatingObjectHandle) as? Bool ?? false
        }
        set {
            
            objc_setAssociatedObject(self,&RotatingObjectHandle,.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    
    func beginRotating() {
        
        guard !self.isRotating else { return }
        
        self.isRotating = true
        self.shouldStopRotating = false
        self.rotate()
    }
    
    
    private func rotate() {
        
        UIView.animate(withDuration: 0.65,delay: 0,options: .curveLinear,animations: {
            self.transform = self.transform.rotated(by: CGFloat(Double.pi))
        },completion: { _ in
            
            if !self.shouldStopRotating {
                
                self.rotate()
            } else {
                
                self.isRotating = false
                self.shouldStopRotating = false
            }
        })
    }
    
    
    func stopRotating() {
        
        self.shouldStopRotating = true
    }
 }