У меня есть настраиваемая ячейка UITableView, в которую я добавил текстовое поле для редактирования, которое отображается и скрывается в зависимости от редактирования Режим. Я также пробовал добавить вертикальную линию, которая отображается при редактировании, и она это делает, но у меня возникают некоторые проблемы с рисованием. Я только что добавил зеленую галочку rightView, чтобы начать работу с отзывами о проверке ввода, и вижу похожие проблемы.
Вот код для ячейки и часть моего cellForRowAtIndexPath.
#import <UIKit/UIKit.h>
@interface EditableCellStyle2 : UITableViewCell {
CGRect editRect;
UITextField *editField;
UIView *lineView;
}
@property (nonatomic, readonly, retain) UITextField *editField;
@property (nonatomic, readonly, retain) UIView *lineView;
@end
#import "EditableCellStyle2.h"
@implementation EditableCellStyle2
@synthesize editField;
@synthesize lineView;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code.
editRect = CGRectMake(83, 12, self.contentView.bounds.size.width-83, 19);
editField = [[UITextField alloc] initWithFrame:editRect];
editField.font = [UIFont boldSystemFontOfSize:15];
editField.textAlignment = UITextAlignmentLeft;
editField.textColor = [UIColor blackColor];
editField.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[self.contentView addSubview:editField];
self.editField.enabled = NO;
self.editField.hidden = YES;
lineView = [[UIView alloc] initWithFrame:CGRectMake(80, 0, 1, self.contentView.bounds.size.height)];
self.lineView.backgroundColor = [UIColor lightGrayColor];
[self.contentView addSubview:lineView];
self.lineView.hidden = YES;
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state.
}
-(void)layoutSubviews
{
[super layoutSubviews]; // layouts the cell as UITableViewCellStyleValue2 would normally look like
editRect = CGRectMake(83, 12, self.contentView.frame.size.width-self.detailTextLabel.frame.origin.x-10, 19);
editField.frame = editRect;
}
- (void)willTransitionToState:(UITableViewCellStateMask)state {
[super willTransitionToState:state];
if (state & UITableViewCellStateEditingMask) {
self.detailTextLabel.hidden = YES;
self.editField.enabled = YES;
self.lineView.hidden = NO;
self.editField.hidden = NO;
}
}
- (void)didTransitionToState:(UITableViewCellStateMask)state {
[super didTransitionToState:state];
if (!(state & UITableViewCellStateEditingMask)) {
self.editField.enabled = NO;
self.editField.hidden = YES;
self.lineView.hidden = YES;
self.detailTextLabel.hidden = NO;
self.editField.text = self.detailTextLabel.text;
}
}
- (void)dealloc {
[editField release];
[lineView release];
[super dealloc];
}
@end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// handling every section by hand since this view is essentially static. Sections 0, 1, 2, and 4 use a generic editable cell.
// Section 3 uses the multiline address cell.
static NSString *CellIdentifier = @"Cell";
EditableCellStyle2 *cell = (EditableCellStyle2 *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 4) {
if (cell == nil) {
cell = [[[EditableCellStyle2 alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
}
// Configure the Odometer
if (indexPath.section == 0) {
NSArray *array = [sectionsArray objectAtIndex:indexPath.section];
NSDictionary *dictionary = [array objectAtIndex:indexPath.row];
cell.textLabel.text = @"Odometer";
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [dictionary objectForKey:@"Odometer"]];
cell.tag = kOdometer;
cell.editField.text = cell.detailTextLabel.text;
cell.editField.placeholder = @"Odometer";
cell.editField.tag = kOdometer;
cell.editField.keyboardType = UIKeyboardTypeNumberPad;
// Create a view for the green checkmark for odometer input validation and set it as the right view.
UIImage *checkImage = [UIImage imageNamed:@"tick.png"];
UIImageView *checkImageView = [[[UIImageView alloc] initWithImage:checkImage] autorelease];
cell.editField.rightView = checkImageView;
cell.editField.rightViewMode = UITextFieldViewModeAlways;
}
return cell;
}
Это еще не все, но все ячейки построены одинаково.
Проблема в том, что в режиме редактирования вертикальные линии будут отображаться правильно. Когда я выхожу из режима редактирования, все ячейки, которые были за пределами экрана, когда я перехожу в нормальный режим, по-прежнему имеют вертикальную линию (она не скрывается). Кроме того, теперь, когда я добавил imageView для индикатора галочки, все ячейки, которые не отображаются при переключении режимов, получают галочку. (только раздел 0 устанавливает его.)
Я также заметил, что если я сделаю cell.setNeedsDisplay, текстовая метка и текстовая метка детали не будут обновляться, если источник данных был обновлен. Мне нужно сделать [self.tableView reloadData], который пропускает любые активные анимации.
Я уверен, что эти проблемы связаны со мной, использующим пользовательскую ячейку + dequeueReusableCellWithIdentifier, но я не могу найти, что именно. Отказ от использования повторно используемых ячеек, похоже, решил вышеуказанные проблемы. Я все еще открыт для отзывов о коде ячейки. Я забыл еще об одной проблеме, которая может быть связана или не связана. В одной из моих ячеек есть кнопка «нажмите, чтобы просмотреть список». Если я ввожу данные в ячейки в режиме редактирования, а затем нажимаю эту кнопку, чтобы выбрать некоторую информацию из списка (он отображает модальное представление таблицы), когда я закрываю модальное представление, все отредактированные данные ячеек возвращаются к своему исходное состояние. Я не вызываю данные перезагрузки, когда отключаю контроллер модального представления. Я думал, что это можно исправить, если не использовать повторно используемые ячейки, но это не так.