drawInRect:withAttributes vs drawInRect:withFont:lineBreakMode:alignment

我正在研究我的应用程序的新版本,并试图replace弃用的消息,但无法超越这一个。

我不明白为什么drawInRect:withAttributes不起作用。 当drawInRect:withFont:lineBreakMode:alignment消息被发送时,代码正确显示,但在drawInRect:withAttributes发送时drawInRect:withAttributes

我使用相同的矩形和字体,我相信是相同的文字样式。 常量只是在图像下方定位矩形,但是对于这两个调用我使用的是相同的矩形,所以我确定矩形是正确的。

(注意下面使用的bs.name是一个NSString对象)

  CGRect textRect = CGRectMake(fCol*kRVCiPadAlbumColumnWidth, kRVCiPadAlbumColumnWidth-kRVCiPadTextLabelYOffset, kRVCiPadAlbumColumnWidth, kRVCiPadTextLabelHeight); NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy]; textStyle.lineBreakMode = NSLineBreakByWordWrapping; textStyle.alignment = NSTextAlignmentCenter; UIFont *textFont = [UIFont systemFontOfSize:16]; 

这不起作用(屏幕上没有画出)使用上面的variables

  [bs.name drawInRect:textRect withAttributes:@{NSFontAttributeName:textFont, NSParagraphStyleAttributeName:textStyle}]; 

这样做的工作(string在屏幕上正确绘制)使用上面相同的variables

  [bs.name drawInRect:textRect withFont:textFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter]; 

任何援助将是伟大的。 谢谢。

要设置文本的颜色,您需要传递属性中的NSForegroundColorAttributeName作为附加参数。

 NSDictionary *dictionary = @{ NSFontAttributeName: self.font, NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: self.textColor}; 

我用drawRect:做了一个UIView drawRect:只包含你提供的代码

 - (void)drawRect:(CGRect)frame { NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy]; textStyle.lineBreakMode = NSLineBreakByWordWrapping; textStyle.alignment = NSTextAlignmentCenter; UIFont *textFont = [UIFont systemFontOfSize:16]; NSString *text = @"Lorem ipsum"; // iOS 7 way [text drawInRect:frame withAttributes:@{NSFontAttributeName:textFont, NSParagraphStyleAttributeName:textStyle}]; // pre iOS 7 way CGFloat margin = 16; CGRect bottomFrame = CGRectMake(0, margin, frame.size.width, frame.size.height - margin); [text drawInRect:bottomFrame withFont:textFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter]; } 

我没有看到这两种方法的输出有什么区别。 也许问题是在你的代码中的其他地方?

Interesting Posts