代码之家  ›  专栏  ›  技术社区  ›  Piotr Tomasik

如何在UITableViewCell的UITextView中一致地绘制NSAttributedString

  •  5
  • Piotr Tomasik  · 技术社区  · 13 年前

    我在使用NSAttributedStrings从UITableViewCell中的UITextViews获取一致结果时遇到问题。

    内部-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
        headerText = [[UITextView alloc]initWithFrame:CGRectZero];
        [headerText setUserInteractionEnabled:NO];
        headerText.tag = HEADER_TEXT;
        [cell.contentView addSubview:headerText]; 
    } else {
        headerText = (UITextView*)[cell.contentView viewWithTag:HEADER_TEXT];
    }
    
    //...setting up attributed strings
    
    
    [headerText setAttributedText:headerString];
    
    CGSize headerSize = [headerText sizeThatFits:CGSizeMake(246, CGFLOAT_MAX)];
    
    headerText.frame = CGRectMake(45, 8, headerSize.width, headerSize.height);
    

    结果:

    Before Scrolling No contentinset

    正如你所看到的,前两个似乎以我所期望/想要的方式绘制了文本。在最后两个例子中,UITextView sizeThatFits方法返回的大小比绘制文本所需的大得多,并且文本在框架中居中,而不是紧挨在框架顶部。这是一个问题,因为我希望能够基于uitextview框架高度来布局其他视图。

    滚动出帧并返回后: enter image description here

    现在,当单元格被重用,并且属性字符串被重新设置时,情况变得更加奇怪。uitextview以不一致的方式绘制文本。

    甚至将contentInsets设置为

    headerText.contentInset = UIEdgeInsetsMake(-8, -8, -8, -8);
    

    没有提供任何一致的结果:

    enter image description here

    使用内容插入集滚动后: enter image description here

    UITextView上是否有其他属性可以让我获得所需的行为?

    1 回复  |  直到 13 年前
        1
  •  8
  •   matt    13 年前

    当设置以前具有不同属性字符串的UITextView的属性字符串时,必须始终首先将UITextView所有与字符串相关的属性设置为nil,例如:

    self.tv.text = nil;
    self.tv.font = nil;
    self.tv.textColor = nil;
    self.tv.textAlignment = NSTextAlignmentLeft;
    self.tv.attributedText = s2;
    

    否则,正如您所发现的,上一个属性字符串的旧特性仍然存在并影响新的属性字符串。

    不过,总的来说,我不得不说,我根本不明白你为什么要使用UITextView。如果您不需要用户能够编辑这些属性字符串,请使用UILabel,或者直接绘制属性字符串,以实现最准确的渲染。NSAttributedString为您提供了测量大小并在该大小范围内绘制所需的所有功能。

    推荐文章