Reputation: 636
The UILabel is created in Interface builder. It is part of a UITableViewCell. Its color is set to red in Interface Builder.
I create the cells here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"notationcell";
NotationCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.notation = [self.notations objectAtIndex:indexPath.row];
UIColor *before = cell.symbolLabel.textColor;
cell.symbolLabel.text = @"new text";
UIColor *after = cell.symbolLabel.textColor;
return cell;
}
Before is red, as intended. But after changing the text the after color becomes UIDeviceWhiteColorSpace 0 1, and the text becomes black. I am using AutoLayout.
Why does changing the text imply the change of its color?
Upvotes: 1
Views: 1338
Reputation: 130
If you want the text color to be permanently red try setting the Label's text color in the delegate method itself rather than from XIB:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"notationcell";
NotationCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.notation = [self.notations objectAtIndex:indexPath.row];
cell.symbolLabel.text = @"new text";
cell.symbolLabel.textColor = [UIColor RedColor];
return cell;
}
Upvotes: 0
Reputation: 636
Found a solution. I created a category:
@implementation UILabel (KeepAttributes)
- (void)setTextWithKeepingAttributes:(NSString *)text{
NSDictionary *attributes = [(NSAttributedString *)self.attributedText attributesAtIndex:0 effectiveRange:NULL];
self.attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
@end
Then used this method to change the text.
Upvotes: 1