Swift iOS - 如何将 subview 添加到窗口的中心?

标签 swift centering subview uiwindow uiscreen

我有一个在 iPhone 和 iPad 上显示的事件指示器。在 iPad 的分屏模式下,它会呈现给调用它的 View 的任何一侧。相反,我希望它显示在窗口屏幕的中间/中央。如果我这样做,无论是在纵向的 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()
}

}

最佳答案

这很简单。关闭自动调整大小蒙版。添加add actInd到窗口,然后设置中心anchors .

actInd.translatesAutoresizingMaskIntoConstraints = false

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

关于Swift iOS - 如何将 subview 添加到窗口的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45521949/

相关文章:

java - 两个数相加,twist就是数的长度可以很大

ios - Sprite 套件中的 SKShapeNode 碰撞检测未检测到碰撞

r - 将 knitr 包的 kable 函数生成的表格居中

ios - 数据未从 JSON 加载到第二个 View Controller 上

ios - 如何从 Firebase 数据库调用帖子 ID

html - 使用 CSS 网格对齐 ALT SYMBOL 和常规文本?

google-maps - 谷歌地图 - 缩放和居中不起作用

ios - 快速拖动 subview 以删除特定位置

iphone - viewDidAppear 用于 subview

iphone - UITableView:以编程方式设置数据源