Swift:核心动画没有动画效果
问题描述:
当谈到Core Animation时,我是一个noobie。我试图实现简单的动画,其中UILabel
从A点移动到B点。我从动画代码示例中获得以下代码,但无法使其工作。标签根本不会移动。我究竟做错了什么?Swift:核心动画没有动画效果
let frame = self.view.frame
let blueBox = UIView(frame: frame)
blueBox.backgroundColor = UIColor(red: 46/255, green: 83/255, blue: 160/255, alpha: 1.0)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 400))
label.center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.layer.position = label.center
var attrsA = [NSFontAttributeName: UIFont(name: "LemonMilk", size: 92), NSForegroundColorAttributeName: UIColor.white]
var a = NSMutableAttributedString(string:"Hello\n", attributes:attrsA)
var attrsB = [NSFontAttributeName: UIFont(name: "LemonMilk", size: 38), NSForegroundColorAttributeName: UIColor.white]
var b = NSAttributedString(string:"World", attributes:attrsB)
a.append(b)
label.attributedText = a
let theAnimation = CABasicAnimation(keyPath: "position");
theAnimation.fromValue = [NSValue(cgPoint: CGPoint(x: screenWidth/2, y: screenHeight/2))]
theAnimation.toValue = [NSValue(cgPoint: CGPoint(x: 100.0, y: 100.0))]
theAnimation.duration = 3.0;
theAnimation.autoreverses = false //true - reverses into the initial value either smoothly or not
theAnimation.repeatCount = 2
blueBox.addSubview(label)
view.addSubview(blueBox)
label.layer.add(theAnimation, forKey: "animatePosition");
答
首先:你不能在label
和add(animation:)
上label.layer
相提并论调用addSubview
。您只能在视图层次结构中为已经设置视图。换句话说,即使你的代码的一切都很好,你也打电话给add(animation:)
太快。尝试引入delay。
二:这些线是虚假:
theAnimation.fromValue = [NSValue(cgPoint: CGPoint(x: screenWidth/2, y: screenHeight/2))]
theAnimation.toValue = [NSValue(cgPoint: CGPoint(x: 100.0, y: 100.0))]
既不fromValue
也不toValue
可以是阵列。摆脱这些大括号。而在Swift 3.0.1和更高版本中,你不需要胁迫NSValue。所以:
theAnimation.fromValue = CGPoint(x: screenWidth/2, y: screenHeight/2)
theAnimation.toValue = CGPoint(x: 100.0, y: 100.0)
三:什么是fromValue
甚至?如果您想从标签已有的位置开始动画,只需省略fromValue
即可。
因此,我修改了代码,就这样结束了,我看到了动画:
label.attributedText = a
blueBox.addSubview(label)
view.addSubview(blueBox)
delay(1) {
let theAnimation = CABasicAnimation(keyPath: "position");
theAnimation.toValue = CGPoint(x: 100.0, y: 100.0)
theAnimation.duration = 3.0;
theAnimation.autoreverses = false //true - reverses into the initial value either smoothly or not
theAnimation.repeatCount = 2
label.layer.add(theAnimation, forKey: "animatePosition");
}
+0
我认为动画仍然不会做你想做的事情,但至少在这些建议中你应该看到一些事情发生。如果没有,请让我知道。 – matt
这可能是一个更容易让你只使用'UIView.animate(withDuration:)' – Pierce
@Pierce但那不回答问题 – matt
@matt - 我知道这就是为什么我没有回答这个问题。我只是在评论中提出建议 – Pierce