2012-05-05 3 views
2

Я много искал, но не нашел ничего полезного, связанного с несколькими настраиваемыми строками, мне нужно создать таблицу настроек для моего приложения, в которой мне нужно загрузить строки из xib-файлов, например:Несколько пользовательских строк UITableView?

СТРОКА 1 = >> XIB 1.
СТРОКА 2 = >> XIB 2.
СТРОКА 3 = >> XIB 3.
СТРОКА 4 = >> XIB 4.

Мой подарок код:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell=nil; 
    //We use CellType1 xib for certain rows 
    if(indexPath.row==0){ 
     static NSString *CellIdentifier = @"ACell"; 
     cell =(ACell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if(cell==nil){ 
      NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"ACell" owner:self options:nil]; 
      cell = (ACell *)[nib objectAtIndex:0]; 
     } 
     //Custom cell with whatever 
     //[cell.customLabelA setText:@"myText"] 
    } 
    //We use CellType2 xib for other rows 
    else{ 
     static NSString *CellIdentifier = @"BCell"; 
     cell =(BCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if(cell==nil){ 
      NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"BCell" owner:self options:nil]; 
      cell = (BCell *)[nib objectAtIndex:0]; 
     } 
     //Custom cell with whatever 
     //[cell.customLabelB setText:@"myText"] 
    } 

    return cell; 
} 

ответ

7

Сначала необходимо создать несколько пользовательских классов UITableViewCell (.h и .m), столько, сколько у вас есть XIb файлы:
Таким образом, вы могли бы CellType1 и CellType2, например.
CellType1.h будет выглядеть как

#import <UIKit/UIKit.h> 
@interface CellType1 : UITableViewCell 

@property(nonatomic,strong) IBOutlet UILabel *customLabel; 

@end 

Затем вы создаете файлы XIb, вы можете использовать тип просмотра по умолчанию, но затем, просто удалить вид, который создается автоматически, заменить, что на UITableViewCell, и изменения класс для CellType1. Сделайте то же самое для CellType2.

Затем в tableViewController, написать cellForRow так:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
UITableViewCell *cell=nil; 
//We use CellType1 xib for certain rows 
if(indexPath.row==<whatever you want>){ 
    static NSString *CellIdentifier = @"CellType1"; 
    cell =(CellType1*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(cell==nil){ 
     NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"CellType1" owner:self options:nil]; 
     cell = (CellType1 *)[nib objectAtIndex:0]; 
     } 
     //Custom cell with whatever 
     [cell.customLabel setText:@"myText"] 
} 
//We use CellType2 xib for other rows 
else{ 
    static NSString *CellIdentifier = @"CellType2"; 
    cell =(CellType2*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(cell==nil){ 
     NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"CellType2" owner:self options:nil]; 
     cell = (CellType2 *)[nib objectAtIndex:0]; 
     } 
     //Custom cell with whatever 
     [cell.customLabel setText:@"myText"] 
} 

return cell; 
} 
+0

Что вы имеете в виду «» – Mateus

+0

Вы говорите, что хотите использовать несколько Xib, я угадываю xib1 для строки n1, xib2 для строки n2 и т. Д. Итак, оператор if/else проверяет строку индекс и на основе того, что вы хотели бы достичь, вы выбираете правильный xib в правильном индексе строки –

+0

Главный вид моего XIB следует изменить для UITableViewCells или просто изменить размер представления? – Mateus

3

Если вы еще не знакомы с загрузкой пользовательской ячейки из xib, проверьте documentation here. Чтобы расширить это до нескольких пользовательских xib, вы можете создать каждую ячейку таблицы в отдельном xib, дать ему уникальный идентификатор ячейки, установить контроллер представления таблиц в качестве владельца файла и подключить каждую ячейку к пользовательской ячейке, которую вы определяете (в docs, они используют tvCell в качестве этой розетки). Затем в вашем методе -tableView:cellForRowAtIndexPath: вы можете загрузить правильный xib (или удалить лишнюю ячейку для повторного использования), проверив, в какую строку вы предоставляете ячейку. Например:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *MyIdentifier1 = @"MyIdentifier1"; 
    static NSString *MyIdentifier2 = @"MyIdentifier2"; 
    static NSString *MyIdentifier3 = @"MyIdentifier3"; 
    static NSString *MyIdentifier4 = @"MyIdentifier4"; 

    NSUInteger row = indexPath.row 

    UITableViewCell *cell = nil; 

    if (row == 0) { 
     cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifer1]; 
     if (nil == cell) { 
      [[NSBundle mainBundle] loadNibNamed:@"MyTableCell1" owner:self options:nil]; 
      cell = self.tvCell; 
      self.tvCell = nil; 
     } 
    } 
    else if (row == 1) { 
     cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifer2]; 
     if (nil == cell) { 
      [[NSBundle mainBundle] loadNibNamed:@"MyTableCell2" owner:self options:nil]; 
      cell = self.tvCell; 
      self.tvCell = nil; 
     } 
    } 
    else if (row == 2) { 
     cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifer3]; 
     if (nil == cell) { 
      [[NSBundle mainBundle] loadNibNamed:@"MyTableCell3" owner:self options:nil]; 
      cell = self.tvCell; 
      self.tvCell = nil; 
     } 
    } 
    else if (row == 4) { 
     cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifer4]; 
     if (nil == cell) { 
      [[NSBundle mainBundle] loadNibNamed:@"MyTableCell4" owner:self options:nil]; 
      cell = self.tvCell; 
      self.tvCell = nil; 
     } 
    } 
    // etc. 

    // Do any other custom set up for your cell 

    return cell; 

} 
+0

Этот метод не работает для меня. Я получаю «UITableView dataSource» должен возвращать ячейку из tableView: cellForRowAtIndexPath: «Мысли? У меня есть ViewController, связанный с каждой ячейкой и пользовательский IBOutlet для каждой ячейки, созданной и подключенной к ячейке. –

Смежные вопросы