storyboard搭建项目_使用 Storyboard 创建基于 Auto Layout 的界面

2012年10月开始学习 iOS 时还没有 Auto Layout, 此技术从 iOS 6 正式支持。在 iPhone 6 发布前,根据泄露的诸多消息,未来的 iPhone 的尺寸会往大屏发展,我后知后觉,静下心,写一篇关于她的文章。

创建项目,快捷键:shift + cmd + n

选择 “Single View Application”

填写项目名称:AutoLayoutDemo

打开 Main.storyboard,选中默认 View Controller,操作以下:

内嵌 Navigation Controller

添加两个视图:UIImageView 和 UITableView,当然 UITableViewCell 也要添加到 UITableView,另外我还加了 UILabel 和 UIImageView 在 UITableViewCell 中,如图:

效果图

结构图

接下来是填充 UITableView,首先给 Controller 加上代理和数据源:

添加代理和数据源

然后添加两个 Outlets,否则数据无法加载,如图:

如果用代码实现,则是: self.autoLayoutTableView.delegate = self;

完成后,初始化数据源。一切就绪后,别着急,我考虑加个 Feature,显得高大上,比如:SWTableViewCell ,如图:

SWTableViewCell

分分钟的事儿,搞定:

界面太怪异,花了20分钟,发现是版本问题,我测试了 0.29 和 0.30,最终用的是官方demo的库。当然,如果不需要 disclosure indicator,则不会发生此问题。

正常界面应该是这样:

预期的界面效果图

ok,接下来就是本篇的重点了,介绍前先看下横屏效果:

横屏效果太粗糙,悲剧!

接下来回到 Main.storyboard,选中 ImageView 和 TableView,操作如下:

非常关键的一步

操作完后,会发现如下图:

自动生成约束关系

我们再看下横屏效果图

使用 Auto Layout 后的横屏效果

但是,如果你仔细的话,会发现 console 出现了异常:

2014-06-07 16:58:28.844 AutoLayoutDemo[616:60b] Unable to simultaneously satisfy constraints.

Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)

Will attempt to recover by breaking constraint

Break on objc_exception_throw to catch this in the debugger.

The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.

我们需要微调视图的坐标,把 ImageView 加高,然后更新约束:

微调坐标,更新视图约束

再次运行,一切正常。最终效果:

最终效果

完成这个 Demo 后,我认为 Auto Layout 为多屏幕尺寸的应用开发带来的福音,主要针对竖屏,横屏是其次,考虑到横屏的应用游戏居多,而应用是不多的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值