Home > Blockchain >  Second ViewController in Xcode project is not the same width as my main ViewController?
Second ViewController in Xcode project is not the same width as my main ViewController?

Time:08-20

I've created a new project in Xcode for iOS. I then created a second ViewController in my project, name "TriviaViewController". However, I'm noticing that the width of my new view controller is not the same as the width of the main view controller that was created by Xcode by default.

The width for the main view controller (ViewController.swift) prints as 414.0 The width of the new view controller (TriviaViewController) I've created prints as 375.0

So when I add a UILabel to the view, and center it, the UILabel does not center.

enter image description here

The code seems pretty straight-forward:

let gameTitle : UILabel = {
    let label = UILabel(frame: CGRect(x: 0, y: 150, width: 300, height: 40))
    label.contentMode = UIView.ContentMode.scaleAspectFit
    label.center.x = self.view.center.x
    label.text = "Trivia"
    label.textAlignment = NSTextAlignment.center
    label.textColor = UIColor.black
    label.backgroundColor = UIColor.white
    label.numberOfLines = 1
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold)
    return label
}()
self.view.addSubview(gameTitle)

If I put this same code in the main ViewController, it centers just fine.

CodePudding user response:

For iPhone 11 the Width of 375.0 is when you have display zoom set for "zoomed" . Width of 414.0 is when you have display zoom set for "standard". Try checking which display zoom you have set, you can check it in settings -> general -> display & brightness -> Display zoom. Maybe you somehow managed to accidentally set display zoom for your project. You can verify this in simulator by manually setting (in simulator) Settings -> Developer -> View -> Zoomed (tap Set) You can also refer to this SO Post.

CodePudding user response:

I discovered the problem: since I'm presenting "TriviaViewController" from the main view controller: "ViewController", the Trivia view controller doesn't know the actual frame width until viewDidAppear is called, and I was setting everything in viewDidLoad.

So in TriviaViewController.swift, moving everything from viewDidLoad() to viewDidAppear() fixed the problem.

  • Related