【问题标题】:UILabel text color changes when text is changed文字改变时UILabel文字颜色改变
【发布时间】:2013-06-21 10:49:56
【问题描述】:

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

如预期的那样,Before 是红色的。但是更改文本后颜色变为 UIDeviceWhiteColorSpace 0 1,文本变为黑色。我正在使用自动布局。

为什么改变文字就意味着改变它的颜色?

【问题讨论】:

    标签: ios uitableview uilabel nib uicolor


    【解决方案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
    

    然后用这个方法改变文字。

    【讨论】:

      【解决方案2】:

      如果您希望文本颜色永久为红色,请尝试在委托方法本身而不是在 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中的设置方式。
      猜你喜欢
      • 2014-10-10
      • 1970-01-01
      • 2012-11-03
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多