OC UITableviewCell的優雅new

韋家冰發表於2017-12-13

以前的程式碼是這樣子的 1、2、3步驟

static NSString *const kXXOOXXXCellIdentifier = @"PSCustomDataPickerTableViewCell";
複製程式碼
 [self.tableView registerNib:[UINib nibWithNibName:kPSInputInfoTableViewCellIdentifier bundle:nil] forCellReuseIdentifier:kPSInputInfoTableViewCellIdentifier];
 [self.tableView registerClass:[PSCustomDataPickerTableViewCell class] forCellReuseIdentifier:kPSCustomDataPickerTableViewCellIdentifier];
複製程式碼
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kPSInputInfoTableViewCellIdentifier;
        return cell;
}
複製程式碼

這裡寫registerClass, 那裡寫Identifier定義, 使用時寫dequeueReusableCellWithIdentifier。 寫來寫去這是有多無聊啊,相當於與三個地方在做一件事,我忍了很久了,為什麼不能一句程式碼解決呢?

我想要的樣子就一句話:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    PSContactsTableViewCell *cell = [PSContactsTableViewCell cellForNibTableView:tableView];
    return cell;
}
複製程式碼

原始碼:UITableViewCell的Categoary

#import <UIKit/UIKit.h>
@interface UITableViewCell (PSInitializeCell)
/**
 獲取Cell--Alloc
 */
+ (instancetype)cellForAllocTableView:(UITableView *)tableView;
/**
 獲取Cell--Nib
 */
+ (instancetype)cellForNibTableView:(UITableView *)tableView;
@end
複製程式碼
#import "UITableViewCell+PSInitializeCell.h"

@implementation UITableViewCell (PSInitializeCell)

+ (instancetype)cellForAllocTableView:(UITableView *)tableView{
    
    
    NSString *cellIdentifier=NSStringFromClass(self);
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {//不存在,註冊再獲取
        [tableView registerClass:[self class] forCellReuseIdentifier:cellIdentifier];
        cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    return cell;
    
}

+ (instancetype)cellForNibTableView:(UITableView *)tableView{
    
    NSString *cellIdentifier=NSStringFromClass(self);
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {//不存在,註冊再獲取
        
        //nib的一般都是對應的類名。如果有些情況不對應,那就不適合這個方法。
        [tableView registerNib:[UINib nibWithNibName:cellIdentifier bundle:nil] forCellReuseIdentifier:cellIdentifier];
        cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    return cell;
    
}

@end
複製程式碼

外: 1.內次都NSString *cellIdentifier=NSStringFromClass(self);可能消耗效能,以後再慢慢研究它(一個類只能一次,又不定義變數),現在先這樣 2.首先註冊registerNib cell,然後使用: 1.dequeueReusableCellWithIdentifier: 2.dequeueReusableCellWithIdentifier:forIndexPath: 一直不知道這兩者有什麼區別?

相關文章