Swift - viewing different position on viewDidLoad and viewDidAppear

那年仲夏 提交于 2020-01-03 01:15:44

问题


I have an understanding problem... I created two similar views (same origin and same size) and section view, While i created those views - one in viewDidLoad and the other in viewDidAppear - when i put similar starting point in the origin x and y of each view that refer to section i get those views in different position. Can someone explain me what is the reason that those views isn't in the same position?

import UIKit

class ViewController: UIViewController {

    @IBOutlet var sec: UIView!

    override func viewDidLoad() {
        let shape = UIView(frame: CGRect(x: sec.frame.width/2, y: sec.frame.height/2, width: 100, height: 100));
        shape.backgroundColor = UIColor.redColor();
        view.addSubview(shape); 
    }

    override func viewDidAppear(animated: Bool) {    
        let shape2 = UIView(frame: CGRect(x: sec.frame.width/2, y: sec.frame.height/2, width: 100, height: 100));
        shape2.backgroundColor = UIColor.greenColor();
        view.addSubview(shape2);
    }
}

回答1:


Reason is because viewDidAppear method called after autolayout engine finished it work, viewDidLoad - before. Before autolayout is done frames of any views on screen are not correct in most cases. You may use method viewDidLayoutSubviews as closest point when autolayout is done and frames are correct. Note that this method can be called multiple times.

Upd. Autolayout used by default for view in UIViewController, as well as for views in storyboard; you added custom views in code, which are don't use autolayout. You should be carefully mixing autolayout and frame-initialized views.



来源:https://stackoverflow.com/questions/38056680/swift-viewing-different-position-on-viewdidload-and-viewdidappear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!