【问题标题】:Drawing text in UITableViewCell在 UITableViewCell 中绘制文本
【发布时间】:2013-05-14 07:20:47
【问题描述】:

我使用以下方法在我的自定义单元格中绘制文本,它工作正常,但我发现部分文本丢失(未显示单元格中的所有文本):

- (void)drawContentView:(CGRect)rect {

    UIColor * textColor = [UIColor blackColor];
    if (self.selected || self.highlighted){
        textColor = [UIColor whiteColor];
    }
    else
    {
        [[UIColor whiteColor] set];
        UIRectFill(self.bounds);
    }

    [textColor set];

    UIFont * textFont = [UIFont systemFontOfSize:16];

    CGSize textSize = [text sizeWithFont:textFont constrainedToSize:rect.size];



    [text drawInRect:CGRectMake(self.frame.size.width-(textSize.width+2  ) ,
                                (rect.size.height / 2) - (textSize.height / 2),
                                textSize.width, textSize.height) withFont:textFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentRight];


}

谢谢,请指教。

【问题讨论】:

  • 你为什么不为此使用 UILabel?

标签: iphone ios objective-c xcode drawrect


【解决方案1】:

尽量让绘图空间大于textSize.width, textSize.heigh

UIFont * textFont = [UIFont systemFontOfSize:16];

CGSize sizeMe = CGSizeMake(300, rect.size.height*1.5);
CGSize textSize = [text sizeWithFont:textFont constrainedToSize:sizeMe];
[text drawInRect:CGRectMake(self.frame.size.width-(textSize.width+10 ) ,
(rect.size.height / 2) - (textSize.height / 2),
textSize.width, textSize.height+(textSize.height*1.5)) withFont:textFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentRight];

【讨论】:

    【解决方案2】:

    也许您应该将决定文本大小的行更改为:

    CGSize textSize = [text sizeWithFont:textFont constrainedToSize:rect.size lineBreakMode: NSLineBreakByWordWrapping];
    

    【讨论】:

      【解决方案3】:

      您没有考虑 sizeWithFont 中的 lineBreakMode。您可能希望使用– sizeWithFont:constrainedToSize:lineBreakMode: 来确定实际大小。

      顺便说一句,当您的约束正好是 rect.size 时,返回值永远不会大于实际的 rect.size。这可能是你想要的。每当我在自定义单元格中处理可变长度的字符串时,我都想知道字符串是否适合并且可能会扩大单个单元格(这当然需要更多的工作)。 如果您这样做,则将约束大小的size.height 设置为非常高的值。 10000.0f 左右。

      【讨论】:

      • 我绑不工作。感谢您的帮助:)
      【解决方案4】:

      您正在创建一个自定义单元格。将文本绘制到其中需要什么?这就是Label的目的,只需添加为子视图并使用它。

      drawInRect 是一种核心图形绘制方法

      根据文档

      使用指定的在当前图形上下文中绘制字符串 边界矩形和字体。此方法绘制尽可能多的字符串 尽可能使用给定的字体和约束。该方法使用 UILineBreakModeWordWrap 换行模式和 UITextAlignmentLeft 对齐。

      我没有看到您在绘制之前获得上下文。因此它没有有效的上下文。因此没有绘制

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-03
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        • 1970-01-01
        相关资源
        最近更新 更多