ios - 如何使用约束从下到上为 UIView 设置动画?
问题描述
我正在以编程方式创建 UIView,之后我将使用约束从下到上为该视图设置动画。但是动画不会显示在这个视图对象上。
overlay!.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.leadingAnchor.constraint(equalTo: vc.view.leadingAnchor, constant: 20).isActive = true
contentView.trailingAnchor.constraint(equalTo: vc.view.trailingAnchor, constant: -20).isActive = true
contentView.addSubview(messageLabel)
messageLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8).isActive = true
messageLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8).isActive = true
messageLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true
messageLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8).isActive = true
let width: CGFloat = vc.view.frame.width - 40 - 16
stringHeight = calculateEstimatedHeight(width: width, text: text) + 16
contentView.heightAnchor.constraint(equalToConstant: stringHeight).isActive = true
bottomConstraint = contentView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: stringHeight)
bottomConstraint.isActive = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
self.showToastViewWithAnimation(viewController: vc)
}
@objc func showToastViewWithAnimation(viewController: Any) {
if let vc = viewController as? ViewController {
vc.view.layoutIfNeeded()
UIView.animate(withDuration: 0.8) {
self.bottomConstraint.constant = -20
vc.view.layoutIfNeeded()
}
}
}
解决方案
我通过评论指出了一些事情,阅读评论,你就会明白你的代码有什么问题,检查下面的代码。
=> 你的代码:overlay!.addSubview(contentView)
@objc func showToastViewWithAnimation(viewController: Any) {
if let vc = viewController as? ViewController {
//vc.view.layoutIfNeeded() - this is not required before updating constraint value
self.bottomConstraint.constant = -20 //update contstraint outside of the animation block
UIView.animate(withDuration: 0.8) {
//vc.view.layoutIfNeeded()
self.overlay?.layoutIfNeeded() //you needs to layout the overlay view, as your other toast views are added in overlay view and not in view of viewcontroller as per your code
}
}
}
推荐阅读
- azure-devops - 从 Azure DevOps 管道部署的 Java Azure 函数表示成功,但未部署任何函数
- wordpress - 混合内容 http 和 https wordpress
- c# - Different version for RestSharp reference(106.10.1) in NuGet package & .Net MVC reference (105.2.3)
- java - 使用 webdriver(selenium) 通过 onclick() 事件调用页面
- variables - 在 JMeter $__timeshift 中使用变量
- c# - 使用 C# 从数据表中删除重复项
- javascript - Safari 在加载本地 js 模块时抛出 CORS 错误
- jenkins - Jenkins“基于角色的授权策略”插件与 OIDC - 如何配置项目角色?
- python - 无法在 python 中使用 matplotlib 和 cartopy 绘制轮廓子图
- javascript - 使用 callable 从客户端调用 express 函数