所以图片说明了一切。我基本上有一个标题,并将标签的宽度设置为整个视图的宽度,我将文本对齐设置为居中。然而,显而易见的是,它向右偏移了一点点。我认为操场视图正在切断视图的一部分。任何人都可以告诉我如何正确地集中UILabel吗?谢谢!
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let title = UILabel(frame: CGRect(x: 0, y: 5, width: view.frame.width, height: 60))
title.textAlignment = .center
title.text = "Hello World!"
title.font = UIFont.systemFont(ofSize: 30, weight: .bold)
title.textColor = .white
self.view.addSubview(title)
}
}
PlaygroundPage.current.liveView = ViewController()
答案 0 :(得分:3)
基于视图控制器在viewDidLoad
中的视图框架设置视图框可能会导致预期的布局,因为调用viewDidLoad
时自动布局尚未完成其布局过程。您应该从viewDidLayoutSubviews
设置标签的框架。例如:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let titleLabel = UILabel(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.textAlignment = .center
titleLabel.text = "Hello World!"
titleLabel.font = UIFont.systemFont(ofSize: 30, weight: .bold)
titleLabel.textColor = .white
self.view.addSubview(titleLabel)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
titleLabel.frame = CGRect(x: 0, y: 5, width: view.frame.width, height: 60)
}
}
PlaygroundPage.current.liveView = ViewController()