Swift iOS - 如何将子视图添加到窗口中心?

4
我有一个在iPhone和iPad上呈现的活动指示器。在iPad的分屏模式下,它会被呈现到调用它的视图的任一侧。我希望它能够在窗口屏幕的中心/中间呈现。如果我这样做,无论是在纵向方向的iPhone还是iPad的分屏模式下,它都会始终位于屏幕的中心。
如何实现这个效果?
MyView: UIViewController{

let actInd = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)


@IBAction fileprivate func buttonPressed(_ sender: UIButton) {

      guard let window = UIApplication.shared.keyWindow else { return }
      //how to add actInd as subview to the window' screen?
      actInd.startAnimating()
}

}

你需要将子视图添加到根视图控制器中。 - OverD
你的措辞让人感觉你希望在iPad“窗口”或“屏幕”处,在“分屏”模式下 - 显示两个应用程序 - 在此“窗口”的中心有一个子视图。换句话说,一个跨越两个应用程序的子视图?这是不可能的。另一方面,如果你想在你的应用程序中心放置一个子视图,只需设置两个约束条件 - centerX和centerX锚点到它的父视图。 - user7014451
2个回答

4
很简单。关闭自动调整大小的蒙版。将add actInd添加到窗口,然后设置中心锚点。 锚点
actInd.translatesAutoresizingMaskIntoConstraints = false

window.addSubview(actInd)
actInd.centerXAnchor.constraint(equalTo: window.centerXAnchor).isActive = true
actInd.centerYAnchor.constraint(equalTo: window.centerYAnchor).isActive = true

@Jeffrey Thomas 谢谢!实际上我一开始就用了这个(我没有在问题中包含它),但我的错误更深层次,导致了错误。无论如何,谢谢! - Lance Samaria

1

窗口是UIView的子类。只需将其添加为其子视图,就像将视图添加到另一个视图中一样。但请记住,窗口在整个应用程序中是共享的,因此每次添加它都会消耗内存,请在完成任务后将其删除。 如果您想将其居中于窗口中,可以使用autoResizingMask或向其添加约束。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接