1

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);
    }
}
Yury
  • 6,044
  • 3
  • 19
  • 41
r.pul
  • 109
  • 2
  • 9

1 Answers1

6

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.

Yury
  • 6,044
  • 3
  • 19
  • 41
  • @r.pul there is no compile errors should be, this is just about how it's all work. Autolayout is pretty new feature (only since iOS 6 or 7). So, before autolayout engine was introduced, all coordinate system was clear and straight, just like you expect in your question. You was manage all coordinates only by frame properties (setting up autoresizing masks sometimes). Time goes, and new devices with new screen resolution presented, so it was more and more hard to manage (resize) all frames by hands. Thats why Apple introduced autolayout engine, based, of course, on existed frame system – Yury Jun 28 '16 at 08:31
  • Thanks a lot for your quick and helpful comment, i was assumed that this is the problem... still it's a bit strange to me... Why the compiler doesn't show any error? what's happened behind the scene.. does he is guessing about the size of those frames of views used autolayout that i refer them on viewDidLoad? – r.pul Jun 28 '16 at 08:32
  • @r.pul you may think about autolayout engine just as about hidden function, that executed before view finally appeared on screen, and this function simply change frames of views, using predefine rules. This function also can be executed when something changes on screen in realtime. – Yury Jun 28 '16 at 08:40