使用 Storyboard 創(chuàng)建基于 Auto Layout 的界面

2012年10月開始學(xué)習(xí) iOS 時(shí)還沒有 Auto Layout, 此技術(shù)從 iOS 6 正式支持。在 iPhone 6 發(fā)布前,根據(jù)泄露的諸多消息,未來的 iPhone 的尺寸會(huì)往大屏發(fā)展,我后知后覺,靜下心,寫一篇關(guān)于她的文章。


創(chuàng)建項(xiàng)目,快捷鍵:shift + cmd + n

選擇 “Single View Application”
填寫項(xiàng)目名稱:AutoLayoutDemo

打開 Main.storyboard,選中默認(rèn) View Controller,操作以下:

內(nèi)嵌 Navigation Controller

添加兩個(gè)視圖:UIImageView 和 UITableView,當(dāng)然 UITableViewCell 也要添加到 UITableView,另外我還加了 UILabel 和 UIImageView 在 UITableViewCell 中,如圖:

效果圖
結(jié)構(gòu)圖

接下來是填充 UITableView,首先給 Controller 加上代理和數(shù)據(jù)源:

添加代理和數(shù)據(jù)源

然后添加兩個(gè) Outlets,否則數(shù)據(jù)無法加載,如圖:

如果用代碼實(shí)現(xiàn),則是: self.autoLayoutTableView.delegate = self;

完成后,初始化數(shù)據(jù)源。一切就緒后,別著急,我考慮加個(gè) Feature,顯得高大上,比如:SWTableViewCell ,如圖:

SWTableViewCell

分分鐘的事兒,搞定:

界面太怪異,花了20分鐘,發(fā)現(xiàn)是版本問題,我測試了 0.29 和 0.30,最終用的是官方demo的庫。當(dāng)然,如果不需要 disclosure indicator,則不會(huì)發(fā)生此問題。


正常界面應(yīng)該是這樣:

預(yù)期的界面效果圖

ok,接下來就是本篇的重點(diǎn)了,介紹前先看下橫屏效果:

橫屏效果太粗糙,悲??!

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

非常關(guān)鍵的一步

操作完后,會(huì)發(fā)現(xiàn)如下圖:

自動(dòng)生成約束關(guān)系

我們?cè)倏聪聶M屏效果圖

使用 Auto Layout 后的橫屏效果

但是,如果你仔細(xì)的話,會(huì)發(fā)現(xiàn) console 出現(xiàn)了異常:

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.

我們需要微調(diào)視圖的坐標(biāo),把 ImageView 加高,然后更新約束:

微調(diào)坐標(biāo),更新視圖約束

再次運(yùn)行,一切正常。最終效果:

最終效果

完成這個(gè) Demo 后,我認(rèn)為 Auto Layout 為多屏幕尺寸的應(yīng)用開發(fā)帶來的福音,主要針對(duì)豎屏,橫屏是其次,考慮到橫屏的應(yīng)用游戲居多,而應(yīng)用是不多的。

如需參考,請(qǐng)見:AutoLayoutDemo



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容