self.view is on the ViewController. Does it have any constraints? I found it had a top and a left constraint. It has a frame for sure. The autolayout system starts from self.view. I mean until self.view the iOS system is still using frame for positioning the views. After that, our views are able to be added with autolayout. So in the viewcontroller, I use self.frame.size.width for the width constraint for my own view is the correct approach to do? Am I right?
Use SCREEN_WIDTH
and It's very easy to get your device size and manage your own view properly:
let SCREEN_WIDTH : CGFloat = UIScreen.main.bounds.width
let SCREEN_HEIGHT : CGFloat = UIScreen.main.bounds.height
For more information you can refer this : link
Example : You should add your own new view programatically.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let SCREEN_WIDTH : CGFloat = UIScreen.main.bounds.width
let SCREEN_HEIGHT : CGFloat = UIScreen.main.bounds.height
let newView = UIView()
newView.translatesAutoresizingMaskIntoConstraints = false
newView.backgroundColor = UIColor.black
newView.frame.size = CGSize(width: SCREEN_WIDTH * 0.5 , height: SCREEN_HEIGHT * 0.5)
self.view.addSubview(newView)
self.view.layoutIfNeeded()
}
}
Here I am giving the frame to the constraints of my customized view. I don't want to give this value in a format of frame.size. I want to use somethings like constraint.constant
. I mean pure autolayout.