【问题标题】:UITableViewCell/UITableView: Dynamic resizing of 2 UILabels in UITableViewCell is flickeringUITableViewCell/UITableView:UITableViewCell 中 2 个 UILabel 的动态调整大小闪烁
【发布时间】:2015-05-15 15:04:12
【问题描述】:

我想在图像中显示类似这样的东西,其中两个 UILabel 垂直紧挨着另一个基于文本的扩展。

这就是我尝试的方式。

对于 label1 我使用 NSMutableAttributedString 以便我可以设置行距。 Label2 是普通的字符串文本。

UITableView 的属性

tableView.estimatedRowHeight = 110
tableView.rowHeight = UITableViewAutomaticDimension

heightForRowAtIndexPath() 未实现,因为这些属性将动态处理高度

在 CellForRowAtIndexPath() 中

var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 15
paragraphStyle.alignment = NSTextAlignment.Right
attrString = NSMutableAttributedString(string: "HUGE TEXT 1")
attrString.addAttribute(NSParagraphStyleAttributeName,     value:paragraphStyle, range:NSMakeRange(0, attrString.length))
myCell.label1.attributedText = attrString
myCell.label2.text = "HUGE TEXT 2"

问题:向下滚动时(新单元格来自向下)没有问题,但是当我向上滚动时(新单元格来自向上)单元格开始闪烁,然后调整大小以适应滚动结束。闪烁仅在 UILabel2 上。对于这种布局,我似乎没有找到任何堆栈溢出的解决方案。

【问题讨论】:

    标签: ios uitableview swift


    【解决方案1】:

    这可以帮助你,在你的 UITableViewCell 中实现这个方法:

    + (CGFloat) cellHeightForContent:(NSString)aContent {
        CGFloat result = 0;
        CGSize textDims = [aContent getCorrectSizeWithFont:[UIFont fontWithName:@"Helvetica" size:13] constrainedToSize:CGSizeMake(kLabelWidth, CGFLOAT_MAX)];
        result = 2 * kMarginHeight + textDims.height;
    
        return result;
    }
    

    此方法返回的值将在heightForRowAtIndexPath方法中使用。

    之后,您需要在 NSString 类别中定义方法 getCorrectSizeWithFont,如下所示:

    - (CGSize)getCorrectSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
    {
        NSMutableDictionary *attrsDictionary = [NSMutableDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    
        NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        [attrsDictionary setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    
        NSMutableAttributedString* attrStrWithLinks = [[NSMutableAttributedString alloc] initWithString:self attributes:attrsDictionary];
        CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrStrWithLinks);
        CGSize sz = CTFramesetterSuggestFrameSizeWithConstraints(framesetter,CFRangeMake(0,0),NULL,CGSizeMake(size.width,CGFLOAT_MAX),NULL);
        if (framesetter) CFRelease(framesetter);
        return CGSizeMake(sz.width,sz.height);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多