Swift-在viewDidLoad和viewDidAppear上查看不同的位置 [英] Swift - viewing different position on viewDidLoad and viewDidAppear

查看:262
本文介绍了Swift-在viewDidLoad和viewDidAppear上查看不同的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个理解上的问题... 我创建了两个相似的视图(相同的原点和相同的大小)和剖面图, 当我创建这些视图时-一个在viewDidLoad中,另一个在viewDidAppear中-当我在引用该节的每个视图的原点x和y中放置相似的起点时,这些视图将处于不同的位置. 有人可以向我解释这些视图不在同一位置的原因是什么?

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);
    }
}

推荐答案

原因是因为viewDidAppear方法是在自动布局引擎完成其工作后调用的,而viewDidLoad是在此之前.在自动布局完成之前,大多数情况下,屏幕上所有视图的框架都不正确.自动布局完成且帧正确时,可以使用方法viewDidLayoutSubviews作为最接近的点.请注意,可以多次调用此方法.

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.

更新. 默认情况下,自动布局用于UIViewController中的view以及情节提要中的视图;您在代码中添加了自定义视图,这些视图不使用自动布局.您应该仔细混合自动布局和帧初始化视图.

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.

这篇关于Swift-在viewDidLoad和viewDidAppear上查看不同的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆