1
嗨,大家好我試圖讓我的動畫去任何一方取決於用戶平移的方式,但它不工作,我不知道什麼是錯的。當我只用一個方向工作時,該手勢正常工作,但是當我將邏輯移至moveLabel()函數時,它不再起作用。動畫甚至沒有開始。我的目標是擁有相同的動畫(因爲我會爲其添加更多細節),但根據平移方向將此特定標籤向左或向右移動。這是我現在的感冒UIViewPropertyAnimator根據平移方向的動畫運動
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labelDummy: UILabel!
var labelAnimation = UIViewPropertyAnimator()
override func viewDidLoad() {
super.viewDidLoad()
labelDummy.center.x = view.bounds.maxX/2
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.moveLabel)))
}
func moveLabel(gesture: UIPanGestureRecognizer){
let trans = gesture.translation(in: view)
if trans.x >= 0{
labelAnimation = UIViewPropertyAnimator(duration: 1.0, curve: .easeInOut) {
let yPos = self.labelDummy.center.y
self.labelDummy.center = CGPoint(x: 100 + (self.labelDummy.frame.size.width/2), y: yPos)
}
}
if trans.x < 0 {
labelAnimation = UIViewPropertyAnimator(duration: 1.0, curve: .easeInOut) {
let yPos = self.labelDummy.center.y
self.labelDummy.center = CGPoint(x: 10 + (self.labelDummy.frame.size.width/2), y: yPos)
}
}
labelAnimation.fractionComplete = abs((trans.x/100))
if gesture.state == .ended{
labelAnimation.fractionComplete = 0
}
print("fractionCompleted: ", labelAnimation.fractionComplete)
}
}
我該如何解決這個問題?
這是工作的代碼:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labelDummy: UILabel!
var labelAnimation = UIViewPropertyAnimator()
override func viewDidLoad() {
super.viewDidLoad()
labelDummy.center.x = view.bounds.maxX/2
// Pan for hele viewen som spiller label animasjon
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.moveLabel)))
// animasjon
labelAnimation = UIViewPropertyAnimator(duration: 1.0, curve: .easeInOut) {
let yPos = self.labelDummy.center.y
self.labelDummy.center = CGPoint(x: 10 + (self.labelDummy.frame.size.width/2), y: yPos)
}
//labelAnimation.startAnimation()
}
func moveLabel(gesture: UIPanGestureRecognizer){
print("retning: ", gesture.velocity(in: view).x)
let trans = gesture.translation(in: view)
print("trans: ", trans)
labelAnimation.fractionComplete = trans.x/100
print("fractionCompletet prøver å settes til : ", trans.x/100)
print(trans.x)
if gesture.state == .ended{
print("-ENDED-")
labelAnimation.fractionComplete = 0
}
print("fractionCompletet: ", labelAnimation.fractionComplete)
}
}