ios - 有没有办法以编程方式使用自动布局扩展为自动布局约束设置动画?
问题描述
- 我正在完全以编程方式创建这个应用程序
我想将 addButton 从右下角动画到 headerLabel 的 centerYAnchor,最好使用这个自动布局扩展(下面的扩展)。
view.addSubview(headerLabel)
headerLabel.setAnchors(top: view.topAnchor, paddingTop: 50, bottom: nil, paddingBottom: 0, left: view.leftAnchor, paddingLeft: 40, right: view.rightAnchor, paddingRight: 40, centerX: nil, centerY: nil, width: 0, height: 0)
view.addSubview(addButton)
addButton.setAnchors(top: nil, paddingTop: 0, bottom: view.bottomAnchor, paddingBottom: 16, left: nil, paddingLeft: 0, right: view.rightAnchor, paddingRight: 16, centerX: nil, centerY: nil, width: 60.0, height: 60.0)
当用户单击按钮时,我希望按钮的 centerYAnchor 向上动画并匹配 headerLabel 的 centerYAnchor。
@objc func addListButtonClicked(sender : UIButton){
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
})
}
任何人都可以帮我解决这个问题或给我一些关于从哪里开始的方向吗?谢谢!
解决方案
一种方法:
为您的 使用“开始”和“结束”约束变量addButton
,然后根据您想要按钮的位置激活/停用它们。
var startConstraint: NSLayoutConstraint!
var endConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(addButton)
// set ONLY right anchor, width and height
addButton.setAnchors(top: nil, paddingTop: 0, bottom: nil, paddingBottom: 0, left: nil, paddingLeft: 0, right: view.rightAnchor, paddingRight: 16, centerX: nil, centerY: nil, width: 60.0, height: 60.0)
// define "starting location" constraint
// bottom of addButton 16-pts from bottom of view
startConstraint = addButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16.0)
// define "ending location" constraint
// centerY of addButton at centerY of headerLabel
endConstraint = addButton.centerYAnchor.constraint(equalTo: headerLabel.centerYAnchor)
// activate the starting constraint
startConstraint.isActive = true
}
然后,当您想要将按钮动画到 headerView 时:
@objc func addListButtonClicked(sender : UIButton) {
// deactivate the start constraint
startConstraint.isActive = false
// activate the end constraint
endConstraint.isActive = true
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
self.view.layoutIfNeeded()
})
}
这也将允许您通过反转顺序和激活状态将按钮设置回其原始位置:
// moves button from bottom up to header view
startConstraint.isActive = false
endConstraint.isActive = true
// moves button from header view down to bottom
endConstraint.isActive = false
startConstraint.isActive = true
推荐阅读
- css - 为父元素添加样式
- css - CSS:代码中设置的样式类组合与用户操作应用的组合问题,想要限制子类
- javascript - 带有母版页/模板的 React Router V4 路由器
- python - 访问参数帮助字符串中的“隐式”元变量值
- javascript - 防止 React-Select 一直为空白
- javascript - 从生成器传播收益,同时以相同的方式使用它们(重用)
- angularjs - 打字稿日期格式不起作用
- hibernate - 尝试使用 wildfly13 部署时出现“NoSuchException”异常
- ios - iOS 应用程序 - iOS 11.4 随机崩溃
- arrays - 过滤 JSON 对象