drawInRect:withAttributes vs drawInRect:withFont:lineBreakMode:alignment

时间:2013-10-09 14:08:29

标签: ios objective-c nsstring drawinrect

我正在处理我的应用程序的新版本,并且正在尝试替换已弃用的邮件,但我无法通过此版本。

我无法弄清楚drawInRect:withAttributes无效的原因。发送drawInRect:withFont:lineBreakMode:alignment邮件时,代码会正确显示,但在发送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];

使用上面的变量

,这不起作用(屏幕上没有画出任何内容)
        [bs.name drawInRect:textRect
             withAttributes:@{NSFontAttributeName:textFont,
                              NSParagraphStyleAttributeName:textStyle}];

这是可行的(使用上面相同的变量在屏幕上正确绘制字符串)

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

任何帮助都会很棒。感谢。

2 个答案:

答案 0 :(得分:36)

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

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

答案 1 :(得分:29)

我制作了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];
}

我认为这两种方法的输出没有任何区别。也许问题出在代码中的其他地方?