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之间的约束关系,添加到他们最近的共同父元素上
//对于有层次关系的两个元素,约束添加到层次较高的父元素上
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章