2014年11月25日 星期二

iOS 6以後,要如何呼叫客製化的tableView Cell

分為Cell是「自定義出來的」或是「已經放在storyboard上的」兩種:

一,自定義出來的:

先來viewDidLoad中加入這行註冊你要call的cell,
[self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
//如果要用xib,那就使用iOS5之後就有的method
//- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);

註冊之後,你就可以在cellForRowAtIndexPath:中直接呼叫UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];

//而不需要如下的傳統寫法
static NSString *CellIdentifier = @"CustomCell";
if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

二,從storyboard上抓
先把你客製化的cell放到你storyboard上的tableView中,然後設定identifier為@"CustomCell"

接下來,直接在cellForRowAtIndexPath:中呼叫cell即可
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];
    
注意:如果你用storyboard的方式,那不可以呼叫registerClass:[CustomCell class] 方法,否則它會建立一組新的cell,而不會直接取用storyboard上畫好的!!!

沒有留言:

張貼留言