【问题标题】:How to display an container view with animation in iOS?如何在 iOS 中显示带有动画的容器视图?
【发布时间】:2014-11-28 01:20:30
【问题描述】:

我想在用户点击原始视图控制器中的按钮时显示我自己的自定义视图,因此我尝试定义以下用户点击按钮时引起的函数:

func show() {
    vc = UIViewController()
    var button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: "hide", forControlEvents: UIControlEvents.TouchDown)
    vc.view.addSubview(button)

    self.addChildViewController(vc)
    self.view.addSubview(vc.view)
    vc.didMoveToParentViewController(self)
}

然而,当用户点击按钮时,容器视图会突然显示在屏幕上,但我想让它显示得更流畅。所以接下来我尝试用动画重写它,但我碰壁了,因为我不知道我应该写什么才能用动画显示它:

transitionFromViewController(self, toViewController: vc, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {() -> Void in
        self.addChildViewController(self.vc)
        self.view.addSubview(self.vc.view)
        }, completion: {
        Bool -> Void in
        self.vc.didMoveToParentViewController(self)
})

这会返回一个错误:'NSInvalidArgumentException', reason: 'Children view controllers <mmmmlvalsllsl.ViewController: 0x7fc980f71f70> and <UIViewController: 0x7fc980f6dd00> must have a common parent view controller when calling -[UIViewController transitionFromViewController:toViewController:duration:options:animations:completion:]'

我觉得应该用方法,但是不知道animations:块写什么代码,completion:块写什么。

如何编写动画代码?

【问题讨论】:

    标签: ios animation swift uicontainerview


    【解决方案1】:

    你可以像这样使用view transitioning

    UIView.transitionWithView(self.view, duration: 0.5, options: .TransitionFlipFromLeft, animations: { _ in
        self.view.addSubview(self.vc.view)
    }, completion: nil)
    

    这将为容器视图的内容更改设置动画(以反映正在添加的子视图),而不是尝试为视图控制器转换本身设置动画。您根本不需要使用transitionFromViewController

    【讨论】:

    • 谢谢!还有self.vc.view,而不是vc.view,因为它在闭包内(无法编辑,因为self 只包含4 个字符)。
    • @Gardecolo 谢谢,已解决。由于这些不一致,这些天我很少使用 Swift。
    • 没问题。顺便说一句,我应该在addViewController 之前还是didMoveToParentViewController 之后编写方法?看起来两者都工作正常,所以想知道更好的方法。
    • @Gardecolo stackoverflow.com/a/10146060/834998 你也应该添加一个willMoveToParentViewController: 调用。
    • 谢谢。稍后我会查看视频,至于willMoveToParentController,它会在您调用addChildViewController 时自动调用。 developer.apple.com/library/ios/Documentation/UIKit/Reference/…:
    【解决方案2】:

    @Greg 答案的 swift 4 版本

    UIView.transition(with: self.view, duration: 0.5, options: .transitionFlipFromLeft, animations: {
                    self.view.addSubview(self.vc.view)
                }, completion: nil)
    

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多