iOS開發-View中frame和bounds區別

來源:互聯網
上載者:User

標籤:

開發中調整View的時候的經常會遇到frame和bounds,剛開始看的時候不是很清楚,不過看了一下官方文檔,frame是確定視圖在父視圖中的位置,和本身的大小,bounds確定可以確定子視圖在當前視圖中的位置,還可以改變View的大小,如果bounds確定大小,那麼View的視圖優先選擇的bounds中的寬高。Center的位置是相對於父座標系中的定位。蘋果官方給了一張圖片供參考:

如果還不是很清晰,可以參考一下frame和bounds的中代碼:

-(CGRect)frame{    return CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height);}-(CGRect)bounds{    return CGRectMake(0,0,self.frame.size.width,self.frame.size.height);}

當然為了更好的理解以上的概念,寫個小Demo實戰了一下,viewDidLoad將圖片添加在View中,然後在圖片上添加一個View:

UIImageView  *girlImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Girl.jpg"]];    girlImageView.frame=CGRectMake(40, 40, 240, 300);    [self.view addSubview:girlImageView];//添加到父視圖中    NSLog(@"girlImageView frame:%@------girlImageView bounds:%@",NSStringFromCGRect(girlImageView.frame),NSStringFromCGRect(girlImageView.bounds));    UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];    childView.backgroundColor = [UIColor yellowColor];    [girlImageView addSubview:childView];    NSLog(@"childView frame:%@-------childView bounds:%@",NSStringFromCGRect(childView.frame),NSStringFromCGRect(childView.bounds));

 具體效果如下:

 

輸出結果:

2015-04-03 11:50:00.326 MyContraint[1929:98282] girlImageView frame:{{40, 40}, {240, 300}}------girlImageView bounds:{{0, 0}, {240, 300}}2015-04-03 11:50:00.327 MyContraint[1929:98282] childView frame:{{0, 0}, {100, 100}}-------childView bounds:{{0, 0}, {100, 100}}

 這個時候如果改變一下UIImageView的bounds,代碼如下:

   UIImageView  *girlImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Girl.jpg"]];    girlImageView.frame=CGRectMake(40, 40, 240, 300);    //改變View中內部原點的位置,同樣可以改變frame的寬高    [girlImageView setBounds:CGRectMake(-30, -30, 240, 230)];    [self.view addSubview:girlImageView];//添加到父視圖中    NSLog(@"girlImageView frame:%@------girlImageView bounds:%@",NSStringFromCGRect(girlImageView.frame),NSStringFromCGRect(girlImageView.bounds));

 圖片效果:

列印效果如下:

2015-04-03 11:57:06.738 MyContraint[2019:102665] girlImageView frame:{{40, 75}, {240, 230}}------girlImageView bounds:{{-30, -30}, {240, 230}}2015-04-03 11:57:06.739 MyContraint[2019:102665] childView frame:{{0, 0}, {100, 100}}-------childView bounds:{{0, 0}, {100, 100}}

 通過以上的代碼的示範,frame和bounds之間的關係應該很清晰了,如果有疑問,歡飲共同探討~

iOS開發-View中frame和bounds區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.