ios - 在 iOS Playground 应用程序中将 View 置于 View Controller 内居中

标签 ios swift swift-playground

我目前正在制作一本 swift Playground 书。在 iPad 上运行时是否可以将 View 置于 View Controller 内的中心?

这是我的 View Controller 的 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 在 View Controller 的 View 中居中?

谢谢!

最佳答案

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

在这个 Xcode Playground 中,请注意 View Controller 的 view 边界与 viewDidLoad() 中的模拟器大小不匹配。模拟器似乎默认为 iPad 大小,但随后以 iPhone 大小显示。然而,在 Xcode 项目 中,情况并非如此 — 您可以viewDidLoad() 中获取当前模拟器边界。

无论哪种情况,放置 subview 的更好位置是在 viewDidLayoutSubviews() 中。 enter image description here

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

关于ios - 在 iOS Playground 应用程序中将 View 置于 View Controller 内居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49476918/

相关文章:

ios - Audiokit 4.5.2 - 无法通过终端中的 cocoa pod 安装

xcode - 在 for 循环内附加图像数组 - swift

swift - for循环不打印数组的输出

swift - 在 Swift 包中包含 Playgrounds 的正确方法是什么?

ios - 无法共享 CloudKit CKShare 记录

iphone - iphone 应用程序可以在安装后更改其主屏幕图标和名称吗?

swift - 函数返回 Swift 后赋值

ios - 以编程方式创建和呈现模态视图 Controller

iphone - 实现 UITableView 委托(delegate)和数据源 : code reuse 的 UIViewController 的子类化

ios - 为什么我不能在 Swift 中使用从一个 UIViewController 传递到另一个(在控制台工作中打印数据)的数据设置标签?