ios - 从 subview 调用 UIView.animate 不起作用

标签 ios xcode swift4

我正在尝试熟悉 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/

相关文章:

ios - 如何防止在 Swift 中从 UIImagePickerController 自动保存图像?

ios11 - 搜索栏未显示在 Swift 4 IOS 11 的导航栏中

ios - 在 CitrusPay 网关 swift ios 中设置卡类型的问题

ios - 在 UIImageView 上使用 Tint 颜色

ios - 如何比较 SKSpritenode 的 2 个纹理

ios - 在Xcode 4.5中执行分析后,iOS应用程序内存泄漏

iphone - UITableViewCell 不换行文本

ios - 序列中可以有 if 语句吗?

IOS:在 iPad 中将 curl 效果作为 map

iOS:如何以编程方式将 UI 从 LTR 更改为 RTL,反之亦然