4
votes

I am having issues with attributed UILabel placed inside custom table view cell. I have a custom cell that contains atrtributed label. I am assigning attributed text from code:

self.paymentLabel.attributedText = attributedString;

When I navigate to next screen by selecting one of the cells, all attributed labels in all cells are resetting.

I tried to reload attributed string in -layoutSubviews method inside cell, but it didn't help. One thing that helped is to reload data in tableView, but it's surely only workaround.

Does anyone has idea what can be the issue?

3
what do you mean by resetting ? is it reset to some initial state? would you paste cellForRowAtIndexPath part related to this cell ?Marcin
have you found any solution? same problem hereH Raval

3 Answers

1
votes

It seems that this issue is not really connected with attributedText but with the way your labels are processed. To check this you can set labels background color at the same code place where you are setting attributedText now and check is color the same after "selecting one of the cells" or not.

1
votes

One way to do this is to set the attributes when the cell is about to be displayed. Here's an example that I use to alter the attributed text in a cell on the fly. It requires finding the UILabel which can be done by tagging it (999 in Interface Builder).

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
  willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if( indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 )
    {
        UILabel * label = (UILabel *)[cell viewWithTag:999];
        NSRange range = [label.attributedText.string rangeOfString: @"®"];
        if (range.length)
        {
            UIFont * font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:12.0];
            NSDictionary * attributes = @{
                                          NSFontAttributeName: [font fontWithSize: 10],
                                          NSBaselineOffsetAttributeName : @10
                                          };
            NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString: label.attributedText.string];
            [string setAttributes: attributes range:range];
            label.attributedText = string;
        }
    }
}
0
votes

The cells of the tableView are being recycled. If you assign the text in code, it will be gone when the cell goes off-screen.

A first thing I would do is to assign the text on the cellForRowAtIndexPath method. If you only want that cell to have that text, you can do it into a if statement:

if (indexPath.section==0 && indexPath.row==0){

    cell.paymentLabel.attributedText = attributedString;

}

without more details about how are you implementing your tableView, I cannot help much more.