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

Fyg*_*ygo 5 animation objective-c uiview ios swift

我试图在我的应用程序中设置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
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

override func viewDidLoad() {
    super.viewDidLoad()

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

    createBackground()
}
Run Code Online (Sandbox Code Playgroud)

我的班级:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢任何想法!

pte*_*fil 2

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

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

如果你搬家

hud = HUD(containingView: view)
hud.show()
Run Code Online (Sandbox Code Playgroud)

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