Как создать свой собственный tableViewCell из Xib - PullRequest
8 голосов
/ 16 ноября 2010

Я хочу создать собственный TableViewCell, на котором я хочу иметь UITextField с возможностью редактирования.Поэтому я создал новый класс с XIB.Добавьте элемент TableViewCell.Перетащите на него UITextField.Добавил розетки в мой класс и соединил их все вместе.В моем методе TableView cellForRowAtIndexPath я создаю свои собственные ячейки, НО они не являются моими настраиваемыми ячейками - это просто обычные ячейки.Как я могу решить эту проблему, и почему это так?спасибо!

// EditCell.ч

#import <UIKit/UIKit.h>


@interface EditCell : UITableViewCell
{
    IBOutlet UITextField *editRow;
}
@property (nonatomic, retain) IBOutlet UITextField *editRow;
@end

// EditCell.m

#import "EditCell.h"


@implementation EditCell
@synthesize editRow;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidUnload 
{
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
    self.editRow = nil; 
}
@end

// в моем коде

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"EditCell";

    EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[EditCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                reuseIdentifier:CellIdentifier] autorelease];
    }
cell.editRow.text = @"some text to test";
return cell;
}

Ответы [ 3 ]

14 голосов
/ 16 ноября 2010

Не используйте инициализатор UITableViewCell, но загрузите ячейку с вашего пера:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"EditCell";

    EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YourNibNameHere" owner:self options:nil];
        cell = (EditCell *)[nib objectAtIndex:0];
    }
    cell.editRow.text = @"some text to test";
    return cell;
}

Конечно, вам нужно указать правильное имя пера.

7 голосов
/ 08 мая 2011

Вы можете загружать пользовательские UITableViewCells из файлов NIB, не создавая сначала подкласс UITableViewCell, но с помощью подкласса вы можете больше настраивать ячейку.

Первое решение без подкласса:

В ViewController:

• Определить ячейку ivar как IBOutlet

UITableViewCell *tableViewCell;

@property (nonatomic, assign) IBOutlet UITableViewCell *tableViewCell;

@synthesize ...

В IB:

• Создайте новый пустой файл NIB и откройте в Интерфейсном Разработчике

• Перетащите ячейку табличного представления из библиотеки в окно документа и откройте ее двойным щелчком

• Настройте ячейку, не забудьтетег добавленных представлений

• Выберите ячейку и добавьте идентификатор (для последующего использования в tableView: cellForRowAtIndexPath:)

• Установите в качестве владельца файла класс контроллера, который будет загружать эту ячейку

• Соединить выход ячейки владельца файла с ячейкой в ​​NIB

В ViewController:

• В tableView: cellForRowAtIndexPath:

static NSString * cellIdentifier = @"SameIdentifierAsInNIB";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"NibFileNameWithoutSuffix" owner:self options:nil];
    cell = tableViewCell;
    // Configure the cell

    self.tableViewCell = nil;
}
// Configure the cell

все установлено

/ * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /

Второе решение, с подклассом:

В редакторе кода:

1. Создать новый подкласс UITableViewCell

2. Добавить метод initWithCoder, добавить настройки

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
      // init magic here
      self.contentView.backgroundColor = [UIColor lightGrayColor];
    }
    return self;
}

3. Добавить метод для настройки значений (например, "setupCellWith:")

- (id)setupCellWith:(NSDictionary *)someSetupDict {

  // more magic here
}

-> Розетки будутбудет добавлено позже из IB

В IB:

4. Создать новый пустой файл XIB

5. Изменить владельца файла = UIViewController

6. Перетащите ячейку TableView из библиотеки

7. Измените ее класс на пользовательский подкласс (см. 1.)

8. Установите свойство идентификатора ячейки // здесь осторожно, так же как в cellForRowAtIndexPath:

9. Подключить точку просмотра владельца файла к ячейке TableView

10. Добавить элементы интерфейса, настроить их правильно (установить класс,…)

11. Создатьнужны utlets через Ctrl-Drag в CustomSubclass.h -> слабый или сильный?-> слабые, сильные только объекты верхнего уровня без предопределенных выходов (например, «представление»)

В редакторе кода:

12. Customize "tableView: cellForRowAtIndexPath: "

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"CustomIdentifier";

    CustomCellSubclass *cell = (CustomCellSubclass *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
      //cell = [[CustomCellSubclass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
      UIViewController *tempController = [[UIViewController alloc] initWithNibName:@"CustomCellSubclassXIBName" bundle:nil];
      cell = (CustomCellSubclass *)tempController.view;
      //[tempController release]; // not needed with ARC
    }
    // Configure the cell...
      [cell setupCellWith:…];

    // do other setup magic here

    return cell;
}
3 голосов
/ 16 ноября 2010

Вам необходимо загрузить xib и получить свою пользовательскую ячейку:

NSArray *uiObjects = [[NSBundle mainBundle] loadNibNamed:@"yourNib" 
                                                   owner:self 
                                                 options:nil];
for (id uiObject in uiObjects) {
     if ([uiObject isKindOfClass:[EditCell class]]) {
          cell = (EditCell *) uiObject;
     }
}

Убедитесь, что вы действительно изменили класс tableViewCell в своей xib на EditCell.Вам также нужно изменить высоту строки tableView до нужного размера.

Еще один способ - просто программно построить вашу ячейку в вашем классе EditCell, что, я считаю, позволит вам быть намного более свободным и точным, чем в InterfaceBuilder:

В EditCell.m:

- (id)initWithStyle:(UITableViewCellStyle)style 
    reuseIdentifier:(NSString *)reuseIdentifier {

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        CGRect textFieldRect = CGRectMake(5, 5, 300, 30);
        UITextField *textField = [[UITextField alloc] initWithFrame:textFieldRect];
        textField.tag = kTextFieldTag;
        [self.contentView addSubview:textField];
        [textField release];
    }
    return self;
}

Затем в вашем tableViewController вы создаете ячейку так, как вы это делали, и извлекаете текстовое поле с тегом.

...