简体   繁体   中英

UILabel with attributed text issue

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?

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.

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;
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM