noblerare
noblerare

Reputation: 11843

How does the layout of iOS screen geometry work?

I am using Xcode 8.2, Swift 3.

I am trying to programmatically create a UIViewController with some textual (and in the future, some graphic) content on the screen. Normally, this would be quite easy to do with the Storyboard but since this ViewController is programmatically created, I have to work like this.

Here is my code so far:

let detailViewController = UIViewController()
detailViewController.view.backgroundColor = UIColor.white

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

let titleLabel = UILabel(frame: CGRect(x: 20, y: 20, width: screenWidth, height: 20))
titleLabel.center = CGPoint(x: screenWidth / 2, y: 100)
titleLabel.backgroundColor = UIColor.red
titleLabel.textAlignment = .center
titleLabel.text = "Scan Results"
titleLabel.font = UIFont.boldSystemFont(ofSize: 14)

let myField: UITextView = UITextView (frame: CGRect(x: 50, y: 50, width: screenWidth, height: 300))
myField.center = CGPoint(x: screenWidth / 2, y: 250)
myField.backgroundColor = UIColor.green

myField.text = <really long string here>

detailViewController.view.addSubview(titleLabel)
detailViewController.view.addSubview(myField)

And this is what I see:

![enter image description here

This raises a lot of questions for me as I am trying to understand how this layout works but can't seem to find any help that makes sense to me.

My screenWidth and screenHeight is 375 and 667 respectively. I am using an iPhone 7. I've positioned my titleLabel in the center but at y: 100. But where the label ended up clearly doesn't look like 1/6 of the way down given that the height of the screen is 667.

So how exactly does textual positioning work? I know that the top left is the origin but that's about it.

Also, I start my text field at x: 50, y: 50 with a width of screenWidth. So why is the text overflowing off the side of the page instead of wrapping around?

Much thanks for any help.

Upvotes: 0

Views: 98

Answers (2)

Fonix
Fonix

Reputation: 11597

I think if you are setting the frame of the different views (via the constructor or otherwise), dont set the .center as well, it will affect its x and y positions hence why their positioning is off

Upvotes: 1

J Manuel
J Manuel

Reputation: 3070

You have to add constraints programmatically, for example:

NSLayoutConstraint(item: myField, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: detailViewController, attribute: NSLayoutAttribute.leadingMargin, multiplier: 1.0, constant: 20.0).isActive = true

myField.widthAnchor.constraint(equalToConstant: 200).isActive = true
myField.heightAnchor.constraint(equalToConstant: 100).isActive = true

Check this answer for more information: https://stackoverflow.com/a/36263784/4077559. I think this is what you are looking for

Upvotes: 1

Related Questions