【问题标题】:NSAttributedString font not overriding xib font the first time the cell is loaded第一次加载单元格时,NSAttributedString 字体不会覆盖 xib 字体
【发布时间】:2020-02-11 22:41:39
【问题描述】:

我有一个带有标签的表格视图单元格。在单元格的 xib 文件中,我在此标签上设置了一个小字体。在我的cellForRow 方法中,我将标签的属性文本属性设置为使用大字体的某个字符串。当我的视图控制器加载时,它最初使用 xib 中指定的小字体。当我将单元格滚动出视图并将其滚动回视图(即重新加载单元格)时,将使用正确的大字体。我怎样才能让它在第一次加载时也采用正确的字体?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      //initialize/dequeue cell from table
      [cell configureLabelWith:[[NSAttributedString alloc] initWithString:@"Hi!"
                                                            attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:24.0]}];
- (void)configureLabelWith:(NSAttributedString *)title {
    self.label.attributedText = title;

【问题讨论】:

    标签: objective-c uitableview xib nsattributedstring


    【解决方案1】:

    在我的例子中,视图控制器的 tableview 在调用cellForRow 之后调用layoutSubviews。放置子视图时,它将标签属性恢复为 xib 中指定的属性(不确定这是否是标准行为)。作为一种解决方法,我将属性字符串存储在单元格中,并在单元格布局后在traitCollectionDidChange 中再次覆盖它,因此我对单元格类进行了以下更改

    @property (nonatomic, strong) NSAttributedString *labelAttributedString;

    - (void)configureLabelWith:(NSAttributedString *)title {
        self.labelAttributedString = title;
        self.label.attributedText = self.labelAttributedString;
    
    - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
        [super traitCollectionDidChange:previousTraitCollection];
        [self configureLabelWith:self.labelAttributedString];
    

    【讨论】:

    • 这在iOS 13上似乎不是问题,只有11和12
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2017-11-03
    • 1970-01-01
    • 2019-08-12
    • 2016-04-08
    • 1970-01-01
    • 2012-04-06
    相关资源
    最近更新 更多