繁体   English   中英

CABasicAnimation与键路径“边界”不起作用

[英]CABasicAnimation with keypath “bounds” not working

我使用CABasicAnimation将以下代码添加到CALayer的动画边界属性中。 但代码似乎不起作用。

    let fromValue = textLabel.layer.bounds
    let toValue = CGRectMake(textLabel.layer.bounds.origin.x, textLabel.layer.bounds.origin.y,   textLabel.layer.bounds.width, textLabel.layer.bounds.height + 50)

    let positionAnimation = CABasicAnimation(keyPath: "bounds")
    positionAnimation.fromValue = NSValue(CGRect: fromValue)
    positionAnimation.toValue = NSValue(CGRect: toValue)
    positionAnimation.duration = 1
    positionAnimation.fillMode = kCAFillModeBoth
    positionAnimation.removedOnCompletion = false

    textLabel.layer.addAnimation(positionAnimation, forKey: "bounds")

你的代码确实有效。 如果运行代码然后在Xcode中打开View Debugging,您将看到标签的高度增加了。 “问题”是iOS 8中的UILabel即使在以这种方式人为增加其图层高度之后,也以相同的方式绘制自己(其文本及其背景,如果有的话)。 (我相信这是因为标签使用基于其文本内容的特殊剪辑区域来绘制自己。)

为了向自己证明这一点,请在普通的UIView(带有彩色背景)而不是标签上进行尝试。 我冒昧地清理你的代码(你不应该以你的方式滥用fillModeremovedOnCompletion - 它只是表明对动画的缺乏理解):

    let fromValue = view2.layer.bounds.height
    let toValue = view2.layer.bounds.height + 50
    CATransaction.setDisableActions(true)
    view2.layer.bounds.size.height = toValue
    let positionAnimation = CABasicAnimation(keyPath: "bounds.size.height")
    positionAnimation.fromValue = fromValue
    positionAnimation.toValue = toValue
    positionAnimation.duration = 1
    view2.layer.addAnimation(positionAnimation, forKey: "bounds")

你会发现它完美无缺。 现在将view2更改回textLabel 它仍然有效,只是没有什么可看的。

另一种向自己证明这一点的方法是删除整个动画,只需更改标签的图层高度:

    self.textLabel.layer.bounds.size.height += 50

你不会看到任何事情发生。 所以动画中没有错误; 这完全取决于标签的绘制方式。

您可以通过更改视图而不是图层来使更改可见:

    self.textLabel.bounds.size.height += 50

然而,另一个“问题”是动画不是动画。 这也是因为标签是以特殊方式绘制的。

所以无论你想要实现它,你都必须以不同的方式去实现它。 您可能在彩色视图前面有一个清晰的标签,并为视图的高度变化设置动画; 我们已经证明这是有效的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM