[BS-13] 創建和注冊UITableViewCell及Storyboard和Xib區別


 

創建和注冊UITableViewCell及Storyboard和Xib區別

// 界面創建完成被調用
- (void)viewDidLoad
{
    [super viewDidLoad];
    /**
     如果采用如下3種方式,為tableView注冊了原形Cell,系統會用注冊的cell作為顯示用的cell和可重用cell,一旦緩沖區中不存在可重用cell,系統會使用注冊的原形Cell新實例化一個Cell供程序使用!
     因此只要注冊了原形Cell,創建cell時就不再需要cell == nil的判斷了。
     */

    //1.純代碼自定義的cell注冊如下:
    [self.tableView registerClass:[HMStatusCell class] forCellReuseIdentifier:ID];

    //2. 使用Xib自定義的cell,注冊如下
     [self.tableView registerNib:[UINib nibWithNibName:@"WZUserCell" bundle:nil] forCellReuseIdentifier:UserCellId];
    
    //3. 使用Storyboard創建ProtoCell,只需設置ProtoCell的reuseIdentifier,系統自動注冊。
    
}

#pragma mark - 數據源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {  
    return self.statusFrames.count;
}

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

    // 官方建議使用以下方法,此方法要求必須預先注冊可重用單元格,否則崩潰!程序發布前的崩潰,可幫助發現問題。
    HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    //HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 一旦在注冊了可重用Cell,以上兩個方法是等價的

    //if (cell == nil) {
    //    cell = [[HMStatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    //} //注冊了原型cell,就不需要再創建了,直接出列使用即可。

    return cell;
}

 

Storyboard和Xib中顯示的TableView有較大的區別:

Storyboard中可以放置各種導航/TabBar/視圖控制器(場景scene),可以設置各個界面之間的關系,屬於重量級的IB工具。

而Xib一般用來設置比較小的局部的UI,如用來自定義某個TableView的cell/footerView/headerView等。另外即使將UITableViewController拖入Xib,也不能在其中添加ProtoCell或普通的cell,強行拖入立即報錯(error: Illegal Configuration: Table views with embedded sections and cells are only supported in storyboard documents)。另外拖入Xib中的UIViewController似乎都不能Embed in導航控制器。

Storyboard(UITableViewController)如下圖:

Xib(UITableView)如下圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM