geekband.02.iOS开发基础(三)View的定位与适配

iOS中界面的布局设置

iOS定位

以屏幕的左上角为原点,向右为x轴,向下为y轴。用了三个结构体来表示一个UIView的形状大小及位置,属性名为frame。CGRect(origin, size),其中origin为CGPoint,size为CGRect。

定位方式

以往在iOS中的定位方式有AutoResizing,但这种方式只能在上下级的views的关系中进行定位。为了能在同一级的view中也能定位,在iOS6之后引入了新的定位方式AutoLayout,现在的iOS工程中使用的都是AutoLayout布局方式。

AutoLayout

使用方式有两种:一种在storyboard里使用拖拽实现,另一种是在代码里实现。
1:按住ctrl键,把一个view1拖到另一个view2上,便可设定相对于view2的自动布局。

AutoLayout约束设定界面

2:代码的方式添加。

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"使用 AutoLayout 的方式";
    UIView *purpleView = [[UIView alloc] init];
    purpleView.backgroundColor = [UIColor purpleColor];
    // 禁止将 AutoresizingMask 转换为 Constraints
    purpleView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:purpleView];
    // 添加 width 约束
    NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:150];
    [purpleView addConstraint:widthConstraint];
    // 添加 height 约束
    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:150];
    [purpleView addConstraint:heightConstraint];
    // 添加 left 约束
    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:100];
    [self.view addConstraint:leftConstraint];
    // 添加 top 约束
    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:200];
    [self.view addConstraint:topConstraint];
}

由此可见,如果全部用代码来添加约束,会产生大量的约束代码,view中各个部件之间的关系就很难看清楚,相对来说,用storyboard中的方式添加约束,使得项目中各个部件之间的关系更加清晰,方便程序员及时的修改及查看效果。

常用的AutoLayout设置面板

Align:

Align

Pin:

Pin

Resize:

Resize

如果有多个UIView组件需要放在一块进行管理,可以将他们embed成一个stackview进行布局。同时在stackview里面也可以设置详细的参数来控制布局的规划。

stackview
stackview 设置

参考文章

[1]AutoLayout的那些事儿,http://www.cocoachina.com/ios/20160616/16732.html
[2]史上比较用心的纯代码实现 AutoLayout,http://www.cocoachina.com/ios/20160616/16732.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,699评论 4 61
  • 希望一首好听的歌可以让你精力充沛的迎接新的一周。 本周分享的歌是我不李志的至此流年各天涯 好歌难遇,当然每个人对好...
    锅包鱼儿阅读 4,914评论 0 2
  • 不知道是怎样、这次的见面与上次完全不一样、不知道是不是受别人影响、不知道是不是他们以前就这样、还是也变了、还是变的...
    小_狼YY阅读 1,481评论 1 0
  • 我记得芥川龙之介在有一本书中说过“所有神的属性中,我最同情的是,神不能自杀”,最后他还是没有抗住精神和生活的压力...
    执剑吟游的诗人阅读 1,445评论 0 0

友情链接更多精彩内容