一、首先我們舉一個小栗子:
1.代碼中先設(shè)置了size,然后再設(shè)置了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 的設(shè)置的順序
// 設(shè)置size
CGRect frame = temp.frame;
frame.size = CGSizeMake(100, 100);
temp.frame = frame;
// 設(shè)置center
temp.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
}
@end
運行結(jié)果如下:

先size,后center
可以看出跟我們預(yù)想的是一樣的,100*100的紅色view在正中間。
然后我們再顛倒下順序。
2.先設(shè)置center,再設(shè)置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 的設(shè)置的順序
// 設(shè)置center
temp.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
// 設(shè)置size
CGRect frame = temp.frame;
frame.size = CGSizeMake(100, 100);
temp.frame = frame;
}
@end
運行結(jié)果如下:

先center,后size
這次的運行結(jié)果卻跟上面的結(jié)果不同。
什么原因呢?
二、問題解釋:
我們看上面的代碼中:
UIView *temp = [[UIView alloc] init];
temp.backgroundColor = [UIColor redColor];
[self.view addSubview:temp];
我們只是創(chuàng)建了名為temp的紅色view,放到了ViewController中,沒有設(shè)置他的X、Y、W、H。
也就是說temp現(xiàn)在是一個“點”,而且這個點在屏幕左上角,我們是看不到的。
1.先size,后center:
在創(chuàng)建了view之后,我們先給了他size,也就是說他的寬高是確定了的(100*100),然后與此同時,他是在左上角的(這也間接證明了上文粗體字),并且center,即中心點,便出現(xiàn)了。

出現(xiàn)在左上角的temp
然后我們通過center,通過控制中心點,來控制temp的位置,這樣很明顯,就可以實現(xiàn)temp出現(xiàn)在屏幕正中間。
2.先center,后size:
在創(chuàng)建了temp之后,我們需要知道,他是一個“點”,這個“點”,既是左上角的點,又是temp的中心點
然后我們通過控制這個看不見的點的“中心點”,來控制它的位置。

看不見的點
然后到現(xiàn)在為止,這個點在正中間,即,center已經(jīng)設(shè)置完畢,在正中間,那么temp的左上角也在正中間(都是同一個點)。
然后我們再設(shè)置寬高的時候,就是以 temp左上角/屏幕中心點, 為(0,0),這樣當(dāng)temp寬高為100的時候,temp的位置就偏移了,我們可以發(fā)現(xiàn),temp的左上角在屏幕正中間。如圖:

注意看temp的左上角的位置
三、總結(jié):
所以到現(xiàn)在,大家應(yīng)該明白了其問題所在。
那么解決辦法也很簡單:
先設(shè)置size,即寬高,再通過設(shè)置center來設(shè)置其位置
說的很啰嗦,但個人覺得挺詳細(xì)的,希望有錯誤之處、不足之處大家可以提出來,我們共同進步哈~~