简体   繁体   中英

How to get bottom edge of the view?

I looked at the following post in order to understand how to get the y-coordinate of the bottom edge of a view: How get bottom y coordinate

It says I can do this: exampleView.frame.maxY

However, when I do this I get 0. Here is my example:

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let thankYouMessage = UILabel()
        self.view.addSubview(thankYouMessage)

        thankYouMessage.text = "Thank You for Installing the Keyboard"
        thankYouMessage.textAlignment = .Center

        thankYouMessage.snp_makeConstraints { (make) -> Void in
            make.right.left.top.equalTo(self.view)
            make.height.equalTo(self.view.frame.height * 0.2)
        }

        print(thankYouMessage.frame.maxY)

        let enableMessage = UILabel()
        self.view.addSubview(enableMessage)
        enableMessage.text = "Enable the keyboard here:"
        enableMessage.textAlignment = .Center
        enableMessage.backgroundColor = UIColor.blackColor()

        enableMessage.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.view)
            make.top.equalTo(self.view).offset(50)
            make.width.equalTo(self.view.frame.width * 0.3)
            make.height.equalTo(self.view.frame.height * 0.1)
        }




    }

The print(thankYouMessage.frame.maxY) returns 0.

I am not sure why this is. Is there some sort of initialization process I need to do to the first view?

The view's frame isn't updated based on its constraints and/or its intrinsic content size until the layout pass has run. The earliest you can get the view's on-screen frame in the view controller is in the viewDidLayoutSubviews method.

You could call layoutIfNeeded or sizeToFit on the view before asking for its frame, but depending on the situation those could still end up giving the wrong answer if called in viewDidLoad .

It happened because you created your label with zero frame and your view is not added to hierarchy in the window in viewDidLoad method. The documentation say's that in viewDidLoad view has been loaded only into memory. And in viewWillAppear it added to hierarchy in the window. Put your print to viewWillAppear for check it or created UILabel() with frame

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM