UIView.transitionWithView打破了加载器的布局

时间:2015-04-16 23:08:38

标签: ios objective-c swift animation uiview

我正在尝试在我的应用中为root-view-controller-change设置动画。交换视图控制器后,我立即加载第二个控制器所需的数据。在加载数据时,我显示了一个加载器(MBProgressHUD)。这是我交换视图控制器的功能:

class ViewUtils {

    class func animateRootViewController(duration: NSTimeInterval, changeToViewController: UIViewController) {
        let window = UIApplication.sharedApplication().delegate?.window?
        if window == nil {
            return
        }
        UIView.transitionWithView(window!,
            duration: duration,
            options: UIViewAnimationOptions.TransitionFlipFromLeft | UIViewAnimationOptions.AllowAnimatedContent,
            animations: {
                window!.rootViewController = changeToViewController
            },
            completion: nil
        )
    }
}

一切都很好,但有一件事 - 它完全打破了装载机。我想象一下发生了什么:2nd view controller 这是旋转时的第二个视图控制器。旋转完成后,加载器显示正常,微调器和文本补间都在圆角矩形中的正确位置。

我真的不明白为什么会这样,请有人向我解释一下,拜托?有没有办法阻止它?

我显示加载器的第二个视图控制器的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    hud = HUD(containingView: view)
    hud.show()

    createBackground()
}

我的hud课程:

class HUD {

    private var hudBG: UIView!
    private var view: UIView!
    private(set) var isShown = false

    init(containingView: UIView) {
        view = containingView
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func show() {
        if !isShown {
            if(hudBG == nil) {
                hudBG = UIView(frame: CGRectMake(0, 0, view.bounds.width, view.bounds.height))
                hudBG.backgroundColor = UIColor(white: 0, alpha: 0.4)
            }
            view.addSubview(hudBG)
            let hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
            hud.mode = MBProgressHUDModeIndeterminate
            hud.labelText = "Cargando"

            hudBG.alpha = 0

            UIView.animateWithDuration(0.3, animations: { () -> Void in
                self.hudBG.alpha = 1
            })
            isShown = true
        }
    }

    func hide() {
        if isShown {
            UIView.animateWithDuration(0.3, animations: {
                () -> Void in
                self.hudBG.alpha = 0
            }, completion: {
                (b) -> Void in
                self.hudBG.removeFromSuperview()
            })
            MBProgressHUD.hideHUDForView(view, animated: true)
            isShown = false
        }
    }
}

非常感谢任何想法!

2 个答案:

答案 0 :(得分:2)

您正在将hud添加到尚未正确初始化的视图中。 如果从xib或storyboard加载视图控制器,则视图及其子视图的大小与从界面加载时的大小相同。

在将视图调整为最终大小后,您必须添加hud。

如果你移动

hud = HUD(containingView: view)
hud.show()

to viewDidLayoutSubviews,它应该可以正常工作。

答案 1 :(得分:0)

在将应用程序从iOS 7移动到iOS 8时,我注意到了类似的问题。在动画期间,尤其是涉及缩放时,视图位置变形。

我很确定这是一个错误。最简单的解决方法是仅为屏幕截图设置动画或查看快照,而不是实际视图 - 这是更多的工作,并且当主动画正在进行时您无法使视图动画化,但通常它是一个更稳定的解决方案。