大家好,我试图让我的动画根据用户平移的方式转到任一侧,但它不起作用,我不知道出了什么问题。当我只使用一个方向时,手势工作正常,但是当我将逻辑移动到 moveLabel() 函数时,它不再工作了。动画甚至没有开始。我的目标是拥有相同的动画(因为我将为其添加更多细节),但让这个特定的标签根据平移方向向左或向右移动。这是我现在的感冒
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)
}
}