我目前正在制作一本 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()
中。
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/