2

In a Swift playground, how do I center a UILabel inside of a UIViewController?

When I use title.center = CGPoint(x: vc.view.frame.width / 2, y: 20) the text goes off of the screen.

This is the problem

problem

If it helps, here's my code.

import UIKit
import PlaygroundSupport


// Set up ViewController and other things
var vc = UIViewController()
vc.view.frame.size.height = 75
vc.view.backgroundColor = .white

let title = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
title.textAlignment = .center
title.center = vc.view.center
title.text = "Which code is correct?"
vc.view.addSubview(title)

PlaygroundPage.current.liveView = vc
jraufeisen
  • 3,005
  • 7
  • 27
  • 43
Jordan Baron
  • 165
  • 1
  • 15

2 Answers2

2

The special problem with swift playgrounds is, that the actual frame of the view controller will only be updated correctly, after the view is loaded / displayed on screen. That means putting the line for centering the label after the line for setting the live view should help:

PlaygroundPage.current.liveView = vc
title.center = vc.view.center
vc.view.addSubview(title)
jraufeisen
  • 3,005
  • 7
  • 27
  • 43
0

If we're talking about top view in hierarchy (i.e. view controller's view), this line should be enough:

title.center = vc.view.center

Otherwise, if you ever want to center your view/label/button/whatever inside any view controller view's subview — the next solution is universal:

title.center = CGPoint(x: parentView.bounds.size.width / 2, y: parentView.bounds.size.height / 2)

If you want to center only horizontally or vertically — modify y or x parameter of CGPoint(x:y:) function correspondingly:

// Center horizontally but with vertical offset of 20 points
title.center = CGPoint(x: parentView.bounds.size.width / 2, y: 20 - title.bounds.size.height / 2)
0xNSHuman
  • 638
  • 5
  • 8