在 iOS Playground 应用中将 viewcontroller 内的视图居中

Center a view inside viewcontroller in iOS Playground app

我目前正在制作一本 swift playground book。 运行 在 iPad 上时是否可以在视图控制器中居中视图?

这是我的视图控制器的 loadView 函数:

override public func loadView() {
    let view = UIView()
    view.backgroundColor = .white
    view.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
    self.view = view

    let frame = CGRect(x: 0, y: 0, width: 375, height: 375)
    let newView = UIView(frame: frame)
    view.addSubview(newView)
}

如何在视图控制器的视图中使 newView 居中?

谢谢!

像这样:

newView.center = self.view.center

您可以尝试使用自动布局来完成:

let frame = CGRect(x: 0, y: 0, width: 375, height: 375)
let newView = UIView(frame: frame)
view.addSubview(newView)
newView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    newView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    newView.leftAnchor.constraint(equalTo: view.leftAnchor),
    newView.rightAnchor.constraint(equalTo: view.rightAnchor),
    newView.widthAnchor.constraint(equalTo: newView.heightAnchor),
])
newView.backgroundColor = UIColor.red

更新

游乐场代码:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .red
        view.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
        self.view = view

        let frame = CGRect(x: 0, y: 0, width: 375, height: 375)
        let newView = UIView(frame: frame)
        newView.backgroundColor = .blue
        view.addSubview(newView)

        newView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            newView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            newView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            // need to define its size too
            newView.heightAnchor.constraint(equalToConstant: 375),
            newView.widthAnchor.constraint(equalTo: view.heightAnchor),
            ])
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

View Controller Lifecycle - Xcode Playground 和 Xcode Project 之间的细微差别...

在这个 Xcode 游乐场中,请注意视图控制器的 view 边界与 viewDidLoad() 中的模拟器大小不匹配。模拟器似乎默认为 iPad 大小,但随后显示为 iPhone 大小。然而,在 Xcode project 中,情况并非如此 — 您 可以 viewDidLoad() 中获取当前模拟器边界.

无论哪种情况,放置子视图的更好位置是 viewDidLayoutSubviews()

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    var yellowView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        yellowView.backgroundColor = .yellow
        yellowView.frame = CGRect(x: 0, y: 0, width: 250, height: 250)
        view.addSubview(yellowView)
    }

    override func viewDidLayoutSubviews() {
        yellowView.center =  CGPoint(x: view.bounds.width / 2, y: view.bounds.height / 2)
    }
}

let vc = MyViewController()
PlaygroundPage.current.liveView = vc