我正在制作一本快速的游乐场书。在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
置于视图控制器的视图中心?
谢谢!
答案 0 :(得分:1)
您可以尝试使用Autolayout:
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()
答案 1 :(得分:0)
在此Xcode游乐场中,请注意,视图控制器的view
边界尚未与viewDidLoad
()中的模拟器大小匹配。该模拟器似乎默认为iPad大小,但随后以iPhone大小显示。但是,在Xcode 项目中,情况并非如此-您可以 在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
答案 2 :(得分:-1)
这样的事情:
newView.center = self.view.center