2017-01-05 59 views
1

enter image description hereIOS添加panGesture到視圖,更改視圖幀,而不是英語流利程度

我視圖添加到self.view,並添加UIPangestureRecognizer到視圖,移動視圖,但不流暢,我能感覺到不流暢, 這是我的代碼,謝謝你幫我

var redView:UIView = UIView(); 
var redFrame:CGRect = CGRect(); 
override func viewDidLoad() { 
    super.viewDidLoad() 
    redView = UIView.init(frame: CGRect.init(x: 0, y: 100, width: KWidth, height: 40)) 
    redView.backgroundColor = UIColor.red 
    self.redFrame = redView.frame; 
    self.view.addSubview(redView); 
    let pan:UIPanGestureRecognizer = UIPanGestureRecognizer.init(target: self, action: #selector(moveFunction(pan:))) 
    self.redView.addGestureRecognizer(pan) 
} 
func moveFunction(pan:UIPanGestureRecognizer) { 
    let point:CGPoint = pan.translation(in: self.view) 
    pan.setTranslation(CGPoint.zero, in: self.view) 
    if pan.state == .changed{ 
     print(point) 
     let redY:CGFloat = redView.frame.origin.y + point.y 
     redView.frame = CGRect.init(x: 0, y: Int(redY), width: KWidth, height: 40) 
    } 
} 
+0

爲什麼每次都重新指定視圖的框架?只有'y'值,什麼在改變。 – dirtydanee

回答

0

使用的UIView動畫集框架上的動畫時長爲0.05。

class func animate(withDuration duration: TimeInterval, animations: @escaping() -> Void) 
+0

對不起,這不是字,我能感覺到不流暢, UIView.animate(withDuration:0.05,動畫:{ 讓REDY:CGFloat的= self.redView.frame.origin.y + point.y self.redView。 frame = CGRect.init(x:0,y:Int(redY),width:KWidth,height:40) }) –

0

我不建議在每次狀態爲.changed時重新分配視圖的框架。只更新手勢識別器視圖的center屬性。另一方面,如果你想到現實生活,當一切開始或停止移動時,它們不會使用相同的速度,它們會加速,並在最終停止之前放慢速度。

因此,我建議將center定位在UIView的動畫塊中,其中.curveEaseInOut選項。

private var originalX: CGFloat = 0.0 
private var originalY: CGFloat = 0.0 

func handlePanGestureRecognizer(_ pan: UIPanGestureRecognizer) { 

    guard let panView = pan.view else { 
     return 
    } 

    // Make sure, the gastureRecognizer's view the topmost view 
    self.view.bringSubview(toFront: panView) 

    // Find coordinates of the gesture recognizer event on the screen 
    var translatedPoint = pan.translation(in: self.view) 

    // The dragging has just started, lets remember the inital positions 
    if pan.state == .began { 
     originalX = panView.center.x 
     originalY = panView.center.y 
    } 

    // increase the coordinates of the gesturerecognizers view by the dragging movement's y coordinate 
    translatedPoint = CGPoint(x: originalX, y: originalY + translatedPoint.y) 

    UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseInOut], animations: { 
     pan.view?.center = translatedPoint 
    } , completion: nil) 
} 

添加此方法,因爲你UIPanGestureRecognizer的作用,它應該給一個更流暢的體驗。

+0

首先,謝謝你幫助我,但我可以感覺到紅色視圖滑動不平滑,我希望紅色視圖滑動平滑 –

+0

您可以將動畫持續時間增加到0.2,這將使xp更平滑,但您會看到運動略有延遲。 – dirtydanee

+0

我想不是時候可以修復這個bug,我不知道該怎麼做,非常抱歉 –