Как правильно Инициализировать пользовательский UITableviewCell?
Я использую следующие 2 метода для возврата пользовательской ячейки:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *key = [self keyForIndexPath:indexPath];
UITableViewCell *cell;
if ([key isEqualToString:DoneButtonCellKey]) {
cell = [self [self doneButtonCellForIndexPath:indexPath];
return cell;
} else {
//code to return default cell...
}
}
Тогда:
- (DoneButtonCell *)doneButtonCellForIndexPath: (NSIndexPath *)indexPath {
DoneButtonCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DoneButtonCellIdentifier forIndexPath:indexPath];
return cell;
}
Каков правильный метод init для использования с ячейкой здесь, чтобы я мог изменить некоторые свойства ячейки при ее инициализации?
EDIT: Я нашел проблему, поскольку методы init/awakeFromNib не вызывались для меня. Я обнаружил ошибку, и я не изменил "Пользовательский класс" из UITableViewCell в свой собственный класс. Теперь awakeFromNib И initWithCoder работают, как описано ниже.
Ответы
Ответ 1
Вы можете внести изменения в класс DoneButtonCell
, либо в
- (void)awakeFromNib
{
.. essential to call super ..
super.awakeFromNib()
//Changes done directly here, we have an object
}
Или метод initWithCoder:
:
-(id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if(self)
{
//Changes here after init'ing self
}
return self;
}
Ответ 2
Вот как я инициализирую пользовательские ячейки
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"FileTableViewCell";
FileTableViewCell *cell = (FileTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FileTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// Configure the cell here...
// Configure the cell.
FileRepresentation* fileRepresentation = _fileList[indexPath.row];
cell.textLabel.text = [self userFilename:[fileRepresentation.fileName stringByDeletingPathExtension]];
cell.detailTextLabel.text = [fileRepresentation modifiedDate];
cell.accessoryView=nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[cell.progressIndicator setHidden:YES];
cell.imageView.image = [UIImage imageNamed:_fileImageName];
// Disable any user interaction while processing a request
if (_fileIsOpen || _creatingDocument || _deletingDocument) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.textColor = [UIColor grayColor];
} else {
cell.textLabel.textColor = [UIColor blackColor];
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
}
}
Ответ 3
Если вы используете Swift, помните, что простой способ обеспечить инициализацию представления при его создании - использовать метод didSet. Например, чтобы сделать UIImageView круглой, вы можете добавить такой код:
@IBOutlet weak var profileImageView: UIImageView! {
didSet {
// Make the profile icon circle.
profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
profileImageView.clipsToBounds = true
}
}
Ответ 4
- Сначала попробуйте деактивировать ячейку, если возможно, используя метод
dequeueReusableCellWithIdentifier
UITableView.
- Если ячейка недоступна (
nil
), используйте [[NSBundle mainBundle] loadNibNamed:@"<#your custom cell nib name#>" owner:nil options:nil][0]
для ее инициализации.
- В вашем пользовательском элементе .m файла выполните инициализацию
initWithCoder:
для пользовательского кода инициализации:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
//your custom initialization code
return self;
}
Это назначенный инициализатор, который вызывается, когда любое представление загружается из nib с помощью loadNibNamed
, как пользовательская ячейка представления таблицы.