我正在尝试为整个屏幕上的UIView设置动画。我在这个UIView中有一个UILabel,其中有一些NSLayoutConstraints。在对UIView的宽度和高度约束进行动画处理时,UILabel约束不会更新。我将标签宽度的约束设置为UIView的宽度锚点,然后在UIView.animate块中调用layoutIfNeeded()。这对标签的约束没有任何作用。
然后,我决定也对标签的约束进行动画处理,因此现在我将标签的宽度动画化为与UIView相同的宽度,并将标签的顶部动画化为25。这可行,除了标签消失的事实动画何时开始,大约有75%的动画从右侧飞入?我不知道为什么会这样。任何帮助,将不胜感激。
动画代码:
guard let cell = collectionView.cellForItem(at: indexPath) as? NeuralNetLayerCollectionCell else {
return
}
let expandingCellView = SlideOverView(frame: cell.bounds)
expandingCellView.center = collectionView.convert(cell.center, to: self)
expandingCellView.textLabel.text = cell.textLabel.text
self.addSubview(expandingCellView)
expandingCellView.widthConstraint.constant = self.frame.width
expandingCellView.heightConstraint.constant = self.frame.height
expandingCellView.labelWidthConstraint.constant = self.frame.width
expandingCellView.labelTopConstraint.constant = 25
UIView.animate(withDuration: 5, animations: {
expandingCellView.center = self.center
expandingCellView.layoutIfNeeded()
})
和约束:
var widthConstraint: NSLayoutConstraint!
var heightConstraint: NSLayoutConstraint!
var labelWidthConstraint: NSLayoutConstraint!
var labelTopConstraint: NSLayoutConstraint!
self.translatesAutoresizingMaskIntoConstraints = false
widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: self.bounds.width)
heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: self.bounds.height)
self.backgroundColor = .white
self.layer.cornerRadius = 25
textLabel.textAlignment = .center
textLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(textLabel)
labelTopConstraint = textLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 25)
let labelLeftConstraint = textLabel.leftAnchor.constraint(equalTo: self.leftAnchor)
labelWidthConstraint = textLabel.widthAnchor.constraint(equalToConstant: self.bounds.width)
let heightConstraintLabel = textLabel.heightAnchor.constraint(equalToConstant: 50)
NSLayoutConstraint.activate([labelTopConstraint, labelLeftConstraint, labelWidthConstraint, heightConstraintLabel, widthConstraint, heightConstraint])