[IOS] 如何更新 UITableview/UICollectionView 的 cell

[更新 2016/02/10]
不知道為什麼,在刪除 cell 時時常會遇到問題 (out of index). 目前找到下面最可靠的解法
 /* ref: 自己的 github */  
 self.TAGS.removeAtIndex((self.collectView.indexPathForCell(cell)?.row)!)  
 self.collectView.deleteItemsAtIndexPaths([self.collectView.indexPathForCell(cell)!])  



由於需要透過使用者 scroll up/down 時添加 UITableView/UICollectionView 中的 cell,昨晚找了些方法,這裡整理一下。

1:  (1)  
2:  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
3:  {  
4:    // Classic start method  
5:  }  
6:  (2)  
7:   - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell, forRowAtIndexPath:(NSIndexPath *)indexPath  
8:  {  
9:    // check if indexPath.row is last row  
10:    // Perform operation to load new Cell's.  
11:  }  
12:  (3)  
13:   var refreshControl:UIRefreshControl!  
14:   override func viewDidLoad()  
15:    {  
16:      super.viewDidLoad()  
17:      self.refreshControl = UIRefreshControl()  
18:      self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")  
19:      self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)  
20:      self.tableView.addSubview(refreshControl)  
21:    }  
22:    func refresh(sender:AnyObject)  
23:   {  
24:     // Code to refresh table view   
25:   }  

首先,方法 (1) 的做法就是當 user 第一次看到第 i 個 cell 時的 function call。意思就是當使用者看到最後一個時候決定幫他更新。這方法最簡單,但是若使用者想連續操作更新時就無法了。
方法(2)則是當使用者 scroll up/down 時即將出現的 cell index 的 function call,但是在小螢幕(昨天是 iphone 4s)下總是不會數到第一個或最後一個,這在使用上讓人猶豫。
最後是方法(3),原來內建就有了 UIRefreshControl!使用上就像 UIGestureRecognizer一樣,可是!昨晚試了一晚都不 work,不論是指定  tableView 的 refreshController 仍然無法。最後原來是需要在 storyboard 上 enable UITableView的 refreshControl! (參考)。另外,似乎 UIRefreshControl 的 default 位置是在上頭,只能 scroll down  to update 而且無法客製化。看來我最後只能選擇方法一了。



參考:StackOverFlow


Comments

Popular posts from this blog

股票評價(Stock Valuation) - 股利折現模型

openwrt feed的使用

R 語言:邏輯回歸 Logistic Regression using R language (二)