iOS可折疊的tableView的簡(jiǎn)單實(shí)現(xiàn)
這里所說的 tableView 折疊,是借助 insert (insertRowsAtIndexPaths:withRowAnimation:) 和 delete (deleteRowsAtIndexPaths:withRowAnimation:) 對(duì)tableView 的 section 進(jìn)行折疊,效果簡(jiǎn)單。
我是初學(xué)者,還請(qǐng)各位看官指教。
搞這個(gè)東西,斷斷續(xù)續(xù)了幾天,現(xiàn)在終于可以告一段落了,雖然離可重用還有距離,但是我想以經(jīng)不遠(yuǎn)了。
遇到的幾個(gè)問題:
1.NSMutableDictionary
NSMutableDictionary 內(nèi)的順序并不是執(zhí)行 setObjectForKey 的順序,順序是亂的(目測(cè)是亂的,不知道是不是有什么規(guī)律,請(qǐng)指教)。
我在這個(gè)東西上繞了一個(gè)大圈子。后來在 AppCode 下面調(diào)試,才發(fā)現(xiàn)這個(gè)問題。為保持插入順序,不得不換成兩個(gè) NSMutableArray ,一個(gè)存 Key,一個(gè)存 Value.
2.headerViewForSection
我想在 numberOfRowsInSection 方法內(nèi)獲取該 section 的 header View ,然后讀取自定義的數(shù)據(jù),比如當(dāng)前狀態(tài)是否是折疊等。
查了一下API,發(fā)現(xiàn)有個(gè) headerViewForSection 方法,但是無論如何,它的值一直都是nil,搞不明白。stackoverflow 上有說須要在使用之前用 tableView 的 registerNib:forHeaderFooterViewReuseIdentifier: 或 registerClass:forHeaderFooterViewReuseIdentifier: 方 法,我試了,沒用。
3.insertRowsAtIndexPaths 和 deleteRowsAtIndexPaths 同 numberOfRowsInSection 的關(guān)系
如果不處理好這個(gè)關(guān)系,大概所有的問題都是這樣的:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 6. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (9), plus or minus the number of rows inserted or deleted from that section (0 inserted, 3 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 2 from section 4 which only contains 0 rows before the update'
大楖是說,numberOfRowsInSection 返回的數(shù)字和 insert / delete 后,section 所包含的行數(shù)不一致。
在 tableView 的 endUpdates 方法之前,應(yīng)該對(duì)標(biāo)志變量做處理。endUpdates 后,會(huì)重新刷新 tableView ,numberOfRowsInSection 會(huì)重新被調(diào)用。
不理想的地方(壞代碼)
同上面講的1和2 ,由于 NSMutableDictionary 的無順序,我將 MutableDictionary 換成了 MutableArray 。
由于無法獲取指定 section 的 headerView ,所以,我只能將以經(jīng)生成的 headerView 記錄到某個(gè) MutableArray 內(nèi),以供使用。
用 xib 設(shè)計(jì)自定義的 UIView
在新建 Objective-C Class 的時(shí)候,只有基類是 UIViewController 的,才能選“With XIB for user interface” 這個(gè)選項(xiàng)。
如果我想自定義一個(gè) UIView , 這個(gè) view 內(nèi)的控件很多,想想就是一件可怕的事情。還好,可以單獨(dú)新建一個(gè) xib 文件。
a, 拖一個(gè)UIView 到 xib 編輯器中,然后更發(fā)這個(gè) view 的size 為 Freeform, 這個(gè) view 就可以自由的改變大小了。
b,更改 class 為自定義的 UIView
c, File's Owner 的 class 還是 NSObject ,不要改。
d, 如何使用這個(gè)自定義的 UIView ?
***,上個(gè)效果圖吧