关于核心动画,我是个菜鸟。我正在尝试实现UILabel
从A点移动到B点的简单动画。我有以下代码是从动画代码示例中获取的,但无法正常工作。标签根本不会动。我究竟做错了什么?
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");
首先:你不能调用addSubview
上label
,并add(animation:)
在label.layer
同日而语。您只能为视图层次结构中已经存在的视图设置动画。换句话说,即使关于代码的一切都很好,您也调用add(animation:)
得太早了。尝试引入延迟。
第二:这些行是伪造的:
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");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句