Autoresizing,Autolayout

Autoresizing,Autolayout,size class之間的關係

1.Autoresizing和Autolayout兩者之間不兼容,若想使用Autoresizing就不能使用Autolayout
2.若想使用size class就必須支持Autolayout

Autoresizing在代碼中的使用

子控件相對於父控件的變化

UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
CGFloat x = self.view.frame.size.width - 100;
CGFloat y = self.view.frame.size.height - 100;
redView.frame = CGRectMake(x, y, 100, 100);
/*
  UIViewAutoresizingFlexibleLeftMargin   距離父控件的左邊是可以伸縮的
  UIViewAutoresizingFlexibleBottomMargin
  UIViewAutoresizingFlexibleRightMargin
  UIViewAutoResizingFlexibleTopMargin
  UIViewAutoresizingFlexibleHeight
  UIViewAutoresizingFlexbleWidth          寬度隨屏幕寬度伸縮變化
  
*/
redView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoResizingFlexibleTopMargin;   //紅色View在父元素的右下角
[self.view addSubview:redView];

Autolayout的使用

Autolayout自iOS6開始引入。是一種“自動佈局”技術,專門用來佈局UI界面的。可以控制任何控件之間的關係,但是autoresizing只能控制子控件和父控件之間的關係

//右下角實現佈局
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
//添加約束
//禁止autoresizing轉化成autolayout
redView.translatesAutoresizingMaskIntoConstrsints = NO;
//高度約束
NSLayoutConstraint *wlcs = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy: NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:100 ];
[redView addConstraint: wlcs];
//約束添加的原則
//同層級的兩個view,約束添加到父元素上
//對於兩個不同層級view之間的約束關係,添加到他們最近的共同父元素上
//對於有層次關係的兩個元素,約束添加到層次較高的父元素上
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章