简体   繁体   English

从子视图调用UIView.animate不起作用

[英]Calling UIView.animate from child view doesnt work

I'm playing around trying to get familiar with swift4 and xcode. 我在玩耍以尝试熟悉swift4和xcode。 I have created a container view which id like to toggle the width on with UIView.animate from the child view. 我创建了一个容器视图,其ID希望从子视图中使用UIView.animate切换宽度。

If I call my toggleWidth function from the containers view controller class, it animates. 如果我从容器视图控制器类调用我的toggleWidth函数,它将设置动画。

If I call it from the child view controller, it changes width, but does not animate. 如果我从子视图控制器调用它,它将更改宽度,但不设置动画。

Can someone explain why? 有人可以解释为什么吗?

Here is the relevant code: 以下是相关代码:

Container 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()
    }
  }
}

Child 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()
  }
}

Appreciate any help that can be given on this one. 感谢在此方面可以提供的任何帮助。

The change to width needs to be done within the animation block, as mentioned in https://developer.apple.com/documentation/uikit/uiview/1622418-animate . 宽度的更改需要在动画块内完成,如https://developer.apple.com/documentation/uikit/uiview/1622418-animate中所述

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()
    }
  }
}

ok, ive gotten back to this after playing with a simple test project, I realised i was calling layoutifneeded on the view i was changing the constraint on, whereas apple clearly state you should call layoutifneeded on the parent object. 好的,我在玩了一个简单的测试项目后回到了这一点,我意识到我在改变约束的视图上调用了layoutifneeded,而苹果明确指出应该在父对象上调用layoutifneeded。 once i changed this, everything started working a charm. 一旦我更改了此设置,一切便开始发挥作用。 hope someone can learn from my mistake. 希望有人可以从我的错误中学到东西。

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

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