Задача C — зачеркнуть метку ячейки таблицы после завершения

Вот некоторый рабочий код, который добавляет галочку к элементу списка дел, когда он завершен:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"ListPrototypeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    XYZToDoItem *toDoItem = [self.toDoItems objectAtIndex:indexPath.row];
    cell.textLabel.text = toDoItem.itemName;
    if (toDoItem.completed) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

    } else {
         cell.accessoryType = UITableViewCellAccessoryNone;
    }    return cell;
}

Что я хочу сделать, так это удалить код галочки и что-то вроде (основная логика):

    if (toDoItem.completed) {
        cellIdentifier.textLabel (NSAttributedString Strikethrough = YES)

    } else {
         cellIdentifier.textLabel (NSAttributedString Strikethrough = NO)
    }    return cell;

Я также пытался изменить NSString на NSAttributedString и NSMutableAttributedString на основе некоторых других вопросов и ответов, которые я видел такой как этот вот так:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary* attributes = @{
                             NSStrikethroughStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle]
                             };
    static NSAttributedString* cellIdentifier = [[NSAttributedString alloc] initWithString:@"ListPrototypeCell" attributes:attributes];
    cell.textLabel.attributedText = cellIdentifier;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    XYZToDoItem *toDoItem = [self.toDoItems objectAtIndex:indexPath.row];
    cell.textLabel.text = toDoItem.itemName;
    if (toDoItem.completed) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;


    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }    return cell;
}

Но я не уверен в точной реализации, например, как это вызвать в методе if (toDoItem.completed). Это должно поддерживаться только iOS7.

Как я могу получить эффект зачеркивания на метке ячейки таблицы, когда элемент будет завершен?


person Eichhörnchen    schedule 15.04.2014    source источник


Ответы (2)


В коде, который вы используете, есть несколько ошибок. Сбой является результатом установки атрибутивной строки в качестве идентификатора ячейки. Оттуда вы должны удалить ячейку из очереди, прежде чем пытаться присвоить значения ее свойствам. Вы также должны инициализировать атрибутивную строку из объекта в массиве toDoItems. В целом, я думаю, что это то, что вы хотели сделать:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"ListPrototypeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];


    XYZToDoItem *toDoItem = [self.toDoItems objectAtIndex:indexPath.row];

    if (toDoItem.completed) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        NSDictionary* attributes = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle]};
        NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:toDoItem.itemName attributes:attributes];

        cell.textLabel.attributedText = attributedString;

    } else {
        cell.textLabel.text = toDoItem.itemName;
        cell.accessoryType = UITableViewCellAccessoryNone;
    } 

    return cell;
}
person Mick MacCallum    schedule 15.04.2014

cellIdentifier.textLabel (NSAttributedString Strikethrough = NO)

Если это действительно то, что вы пытаетесь сделать, измените «cellIdentifier» на «cell» и используйте метод «setAttributedText», чтобы установить NSAttributedString. Идентификатор ячейки — это только строка идентификатора, которая используется для удаления из очереди и повторного использования ячеек. Вам нужно установить текст в UITableViewCell :

NSAttributedString *attributedString; 
//Format your string
[cell.textLabel setAttributedText:attributedString];

ИЗМЕНИТЬ:

В коде, который вы добавили, многие вещи неверны. Во-первых, термин «идентификатор ячейки» обычно используется для описания текста, который вы вводите при исключении из очереди или создании ячейки.

NSString *cellIdentifier = @"ListPrototypeCell";
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

во-вторых, если вы не используете раскадровку или xib, ячейки не создаются автоматически. Добавить :

if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

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

NSString *cellIdentifier = @"ListPrototypeCell";
    NSDictionary* attributes = @{
                                 NSStrikethroughStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle]
                                 };

    NSAttributedString* attributedText = [[NSAttributedString alloc] initWithString: @"The striked text" attributes:attributes];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    XYZToDoItem *toDoItem = [self.toDoItems objectAtIndex:indexPath.row];

    if (toDoItem.completed) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.textLabel.text = nil;
        cell.textLabel.attributedText = attributedText;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.text = toDoItem.itemName;
        cell.textLabel.attributedText = nil;
    }
    return cell;
person Emilie    schedule 15.04.2014