drawInRect:withAttributes vs drawInRect:withFont:lineBreakMode:alignment

Ros*_*tle 30 objective-c nsstring ios drawinrect

我正在开发我的应用程序的新版本,并且我正在尝试替换已弃用的消息,但我无法通过这个消息.

我无法弄清楚为什么drawInRect:withAttributes不起作用.drawInRect:withFont:lineBreakMode:alignment发送消息时代码正确显示,但drawInRect:withAttributes发送时不起作用.

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

(注意下面使用的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];
Run Code Online (Sandbox Code Playgroud)

使用上面的变量,这不起作用(屏幕上没有任何内容)

        [bs.name drawInRect:textRect
             withAttributes:@{NSFontAttributeName:textFont,
                              NSParagraphStyleAttributeName:textStyle}];
Run Code Online (Sandbox Code Playgroud)

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

        [bs.name drawInRect:textRect
                   withFont:textFont
              lineBreakMode:NSLineBreakByWordWrapping
                  alignment:NSTextAlignmentCenter];
Run Code Online (Sandbox Code Playgroud)

任何援助都会很棒.谢谢.

Hir*_*ren 36

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

NSDictionary *dictionary = @{ NSFontAttributeName: self.font,
                              NSParagraphStyleAttributeName: paragraphStyle,
                              NSForegroundColorAttributeName: self.textColor};
Run Code Online (Sandbox Code Playgroud)


Are*_*lko 29

我做了一个UIViewdrawRect:仅含您所提供的代码

- (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];
}
Run Code Online (Sandbox Code Playgroud)

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

  • 好吧,我想出来了,这是一种呃(大多数情况下都是如此).谢谢你的建议!我用的是:[[UIColor lightGrayColor] set]; 设置文本颜色,这适用于早期版本的drawInRect:在较新的版本中,您将文本颜色设置为属性.所以它工作,它只是在黑色背景上绘制黑色文本.我无法发布答案,因为我太新用户了. (3认同)