我正在尝试熟悉 swift4 和 xcode。我创建了一个容器 View ,它喜欢从 subview 中使用 UIView.animate 切换宽度。
如果我从容器 View Controller 类调用我的toggleWidth 函数,它就会产生动画。
如果我从 subview Controller 调用它,它会改变宽度,但不会产生动画。
谁能解释一下为什么?
相关代码如下:
容器 Controller
class ViewController: UIViewController {
@IBOutlet weak var menuContainer: UIView!
@IBOutlet weak var menuWidth: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
toggleMenu()
}
func toggleMenu() {
menuWidth.constant -= 100
UIView.animate(withDuration: 5) {
self.menuContainer.layoutIfNeeded()
}
}
}
子 Controller
class MenuController : UITableViewController {
@IBOutlet weak var homeCell: UITableViewCell!
override func viewDidLoad() {
let tap = UITapGestureRecognizer(target: self, action: #selector(MenuController.imageTapped))
homeCell.addGestureRecognizer(tap)
homeCell.isUserInteractionEnabled = true
}
@objc func imageTapped()
{
(self.parent as! ViewController).toggleMenu()
}
}
感谢对此问题提供的任何帮助。
最佳答案
如 https://developer.apple.com/documentation/uikit/uiview/1622418-animate 中所述,宽度的更改需要在动画 block 内完成.
class ViewController: UIViewController {
@IBOutlet weak var menuContainer: UIView!
@IBOutlet weak var menuWidth: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
toggleMenu()
}
func toggleMenu() {
UIView.animate(withDuration: 5) {
self.menuWidth.constant -= 100
self.menuContainer.layoutIfNeeded()
}
}
}
关于ios - 从 subview 调用 UIView.animate 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49837698/