ios - 如何使用drawInRect :withAttributes: instead of drawAtPoint:forWidth:withFont:fontSize:lineBreakMode:baselineAdjustment: in iOS 7

标签 ios nsstring ios7

此方法在 iOS 7.0 中已弃用:

drawAtPoint:forWidth:withFont:fontSize:lineBreakMode:baselineAdjustment:

现在使用 drawInRect:withAttributes: 代替。

我找不到 fontSize 和 baselineAdjustment 的 attributeName。

编辑

感谢@Puneet 的回答。

实际上,我的意思是如果没有这些 key ,如何在iOS 7中实现这个方法?

像下面的方法:

+ (CGSize)drawWithString:(NSString *)string atPoint:(CGPoint)point forWidth:(CGFloat)width withFont:(UIFont *)font fontSize:(CGFloat)fontSize
           lineBreakMode:(IBLLineBreakMode)lineBreakMode
      baselineAdjustment:(UIBaselineAdjustment)baselineAdjustment {
    if (iOS7) {
        CGRect rect = CGRectMake(point.x, point.y, width, CGFLOAT_MAX);

        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = lineBreakMode;

        NSDictionary *attributes = @{NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle};

        [string drawInRect:rect withAttributes:attributes];

        size = CGSizeZero;
    }
    else {
        size = [string drawAtPoint:point forWidth:width withFont:font fontSize:fontSize lineBreakMode:lineBreakMode baselineAdjustment:baselineAdjustment];
    }
    return size;
}

我不知道如何将fontSizebaselineAdjustment 传递给

属性 字典。

例如

NSBaselineOffsetAttributeName 键应该传递一个 NSNumer 给它,但是 baselineAdjustmentEnum

难道没有其他方法可以传递这两个变量吗?

最佳答案

您可以使用 NSDictionary 并像这样应用属性:

NSFont *font = [NSFont fontWithName:@"Palatino-Roman" size:14.0];

NSDictionary *attrsDictionary =

[NSDictionary dictionaryWithObjectsAndKeys:
                              font, NSFontAttributeName,
                              [NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil];

使用 attrsDictionary 作为参数。

引用:Attributed String Programming Guide

引用:Standard Attributes

迅速: IN String drawInRect 不可用,但我们可以使用 NSString 代替:

let font = UIFont(name: "Palatino-Roman", size: 14.0)
let baselineAdjust = 1.0
let attrsDictionary =  [NSFontAttributeName:font, NSBaselineOffsetAttributeName:baselineAdjust] as [NSObject : AnyObject]
let str:NSString = "Hello World"
str.drawInRect(CGRectZero, withAttributes: attrsDictionary)

关于ios - 如何使用drawInRect :withAttributes: instead of drawAtPoint:forWidth:withFont:fontSize:lineBreakMode:baselineAdjustment: in iOS 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442653/

相关文章:

ios - 运行 iOS 8.2 的 ipad 中不显示相机

ios - UIView重现时如何恢复动画?

ios - 在后台每 X 分钟执行一次函数不起作用

ios - 使用 UIWebview 向 Node.js 函数发送消息

iphone - 我可以从 iOS 模拟器中访问 App Store 吗?

ios - 在 Xcode 11 中构建时系统重新启动

iphone - 使用 initWithBytes :length:encoding NSData 到 NSString

ios - 匹配一个 NSString 和一个 UILabel 的文本

ios - 在 nsstring 中显示视频文件的长度,格式为 MM :SS

uitableview - 实现 heightForRowIndexPath : in iOS 7, 但在 iOS 8 中使用编译时宏删除它