最近開始做 iOS 的項目. 之前的 Android 開發(fā)經(jīng)驗導致有的時候總是有一些思維定勢繞不過來(不認真看文檔), 導致踩了一些不應該踩的坑.
1. UITableView 的 reloadData 的作用
剛開始看到 UITableView 的時候, 第一反應就是這貨不就是一個 ListView. 所以看到 reloadData 這個函數(shù)的時候也沒有細看文檔, 就以為是 notifyDataSetChanged 一樣的作用.
當數(shù)據(jù)變化比較大的時候, 比如刪掉一個, 然后添加了10個之類的. 就直接 reload 了. 結果自然就造成了很多奇怪的現(xiàn)象, 讓我都開始懷疑人生. 后來看到了文檔, 文檔里明確說不能在 beginUpdate 和 endUpdate 之間調(diào)用. 真是死的心的都有了.
文檔的原文:
Call this method to reload all the data that is used to construct the table, including cells, section headers and footers, index arrays, and so on. For efficiency, the table view redisplays only those rows that are visible. It adjusts offsets if the table shrinks as a result of the reload. The table view’s delegate or data source calls this method when it wants the table view to completely reload its data. It should not be called in the methods that insert or delete rows, especially within an animation block implemented with calls to beginUpdates() and endUpdates().
2. 沒有提供準確的 estimate height 導致 TableView 滾動狀態(tài)出錯
iOS 8 后 UITableView 提供了 Cell 的自適應機制. 方法也簡單, 設置 estimatedHeight, 然后把 cellHeight 設成 UITableViewAutomaticDimension 即可.
在 Android 開發(fā)中自適應是一種天然的選擇, 因為 Android 一開就面對各種奇怪尺寸的屏幕. 但是 iOS 設備一開始只有一種尺寸, 每一個設計圖都可以精確到每一個 px. 所以自適應是后期引入的. 雖然沒有具體考古過, 但是我想 UITableView 在設計支出一定也是沒有考慮過自適應高度這一點.
即使在新的機制中, 我們依然要提供 estimatedHeight. 剛開始我以為這個只是一個隨便給的值. 所以即使我的頁面每一個 Cell 的高度都是不一樣. 我依然隨便提供了一個的數(shù)值.
后果當然很嚴重, 當我滾動 TableView 的時候就會出現(xiàn)一些奇怪的跳動. 有時候甚至會觸發(fā)不停的來回滾動. 我的表情是這樣的:
老老實實地滾回去看文檔: Working with Self-Sizing Table View Cells. 里面提到:
Additionally, try to make the estimated row height as accurate as possible. The system calculates items such as the scroll bar heights based on these estimates. The more accurate the estimates, the more seamless the user experience becomes.
人與人的之間的信任都沒有了. 不是說自適應!! accurate 和 estimated 對不上啊!!!
后續(xù)提供了比較精確的 estimated height. 滾動終于正常.