iOS Swift Playgrounds视图不居中

时间:2018-03-15 23:29:55

标签: ios swift autolayout swift-playground

所以图片说明了一切。我基本上有一个标题,并将标签的宽度设置为整个视图的宽度,我将文本对齐设置为居中。然而,显而易见的是,它向右偏移了一点点。我认为操场视图正在切断视图的一部分。任何人都可以告诉我如何正确地集中UILabel吗?谢谢!

Playground View

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()

1 个答案:

答案 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()