Ios UILabel文本颜色在文本更改时更改
UILabel是在Interface builder中创建的。它是UITableViewCell的一部分。其颜色在Interface Builder中设置为红色 我在这里创建单元格:Ios UILabel文本颜色在文本更改时更改,ios,uitableview,uilabel,nib,uicolor,Ios,Uitableview,Uilabel,Nib,Uicolor,UILabel是在Interface builder中创建的。它是UITableViewCell的一部分。其颜色在Interface Builder中设置为红色 我在这里创建单元格: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"notationcell"
- (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,文本变为黑色。我正在使用自动布局
为什么更改文本意味着更改其颜色?找到了一个解决方案。我创建了一个类别:
@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
然后使用此方法更改文本。找到了解决方案。我创建了一个类别:
@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
然后使用此方法更改文本。如果希望文本颜色永久为红色,请尝试在委托方法本身而不是在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;
}
如果希望文本颜色永久为红色,请尝试在委托方法本身而不是在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;
}
是的,这是一个解决方案,但我希望设置这些内容,并在Interface Builder中正确显示,因为我必须与需要查看布局的人一起工作。除了颜色,还有很多其他属性,应该保持在IB中设置的方式。是的,这是一个解决方案,但我希望设置这些属性,并在Interface Builder中正确显示,因为我必须与需要查看布局的人一起工作。除了颜色,还有很多其他属性,这些属性应该保持在IB中设置的方式。