美文网首页
iOS中关于center和size的设置的顺序问题

iOS中关于center和size的设置的顺序问题

作者: 愿你年年多聚无离散 | 来源:发表于2017-08-02 11:58 被阅读0次

    一、首先我们举一个小栗子:

    1.代码中先设置了size,然后再设置了center

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UIView *temp = [[UIView alloc] init];
        temp.backgroundColor = [UIColor redColor];
        [self.view addSubview:temp];
        
        // center 和 size 的设置的顺序
        // 设置size
        CGRect frame = temp.frame;
        frame.size = CGSizeMake(100, 100);
        temp.frame = frame;
        
        // 设置center
        temp.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
        
    }
    
    @end
    

    运行结果如下:


    先size,后center

    可以看出跟我们预想的是一样的,100*100的红色view在正中间。
    然后我们再颠倒下顺序。

    2.先设置center,再设置size:

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UIView *temp = [[UIView alloc] init];
        temp.backgroundColor = [UIColor redColor];
        [self.view addSubview:temp];
        
        // center 和 size 的设置的顺序
        // 设置center
        temp.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
        // 设置size
        CGRect frame = temp.frame;
        frame.size = CGSizeMake(100, 100);
        temp.frame = frame;
    
    }
    
    @end
    

    运行结果如下:


    先center,后size

    这次的运行结果却跟上面的结果不同。
    什么原因呢?

    二、问题解释:

    我们看上面的代码中:

        UIView *temp = [[UIView alloc] init];
        temp.backgroundColor = [UIColor redColor];
        [self.view addSubview:temp];
    

    我们只是创建了名为temp的红色view,放到了ViewController中,没有设置他的X、Y、W、H。
    也就是说temp现在是一个“点”,而且这个点在屏幕左上角,我们是看不到的。

    1.先size,后center:

    在创建了view之后,我们先给了他size,也就是说他的宽高是确定了的(100*100),然后与此同时,他是在左上角的(这也间接证明了上文粗体字),并且center,即中心点,便出现了。

    出现在左上角的temp

    然后我们通过center,通过控制中心点,来控制temp的位置,这样很明显,就可以实现temp出现在屏幕正中间。

    2.先center,后size:

    在创建了temp之后,我们需要知道,他是一个“点”,这个“点”,既是左上角的点,又是temp的中心点
    然后我们通过控制这个看不见的点的“中心点”,来控制它的位置。

    看不见的点
    然后到现在为止,这个点在正中间,即,center已经设置完毕,在正中间,那么temp的左上角也在正中间(都是同一个点)。
    然后我们再设置宽高的时候,就是以 temp左上角/屏幕中心点, 为(0,0),这样当temp宽高为100的时候,temp的位置就偏移了,我们可以发现,temp的左上角在屏幕正中间。如图:
    注意看temp的左上角的位置

    三、总结:

    所以到现在,大家应该明白了其问题所在。
    那么解决办法也很简单:
    先设置size,即宽高,再通过设置center来设置其位置

    说的很啰嗦,但个人觉得挺详细的,希望有错误之处、不足之处大家可以提出来,我们共同进步哈~~

    相关文章

      网友评论

          本文标题:iOS中关于center和size的设置的顺序问题

          本文链接:https://www.haomeiwen.com/subject/uoyelxtx.html