UILabel是在“界面”构建器中创建的。它是UITableViewCell的一部分。它在Interface Builder中的颜色设置为红色。
我在这里创建了单元格:
- (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;
}
之前是红色的,如预期的那样。但更改文本后,后颜色变为UIDeviceWhiteColorSpace 0 1,文本变为黑色。我正在使用AutoLayout。
为什么更改文字意味着改变颜色?
答案 0 :(得分:1)
找到解决方案。我创建了一个类别:
@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
然后使用此方法更改文本。
答案 1 :(得分:0)
如果您希望文本颜色永久为红色,请尝试在委托方法本身而不是XIB中设置Label的文本颜色:
- (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;
}