将属性应用于 iOS 中的文本

Applying attributes to text in iOS

我正在将属性应用于我的文本,如下所示:

 //Great the number string and the rect to put it in
    NSString *numberOne = @"1";
    CGRect numberRect = CGRectMake(47, 100, 50, 50);
    //Create the attributes
    UIFont *font = [UIFont fontWithName:@"Academy Engraved LET" size:60];
    NSParagraphStyle *paragraphStyle = [NSParagraphStyle defaultParagraphStyle];
    NSDictionary *numberOneAttributes = @{NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font, NSForegroundColorAttributeName: [self darkGoldColor]};
    [numberOne drawInRect:numberRect withAttributes:numberOneAttributes];

我不明白数组的初始化。为什么要用NSParagraphStyleAttributeName: paragraphStyle,第一项不应该是key吗?这本字典的键在哪里?对此的任何指示都会很棒。谢谢

你不在这里初始化任何数组。 numberOneAttributes 是一个字典。如果你格式化一点可以更具可读性:

NSDictionary *numberOneAttributes = @{
    NSParagraphStyleAttributeName: paragraphStyle,
    NSFontAttributeName: font, 
    NSForegroundColorAttributeName: [self darkGoldColor]
};

这些是键值对。 NSParagraphStyleAttributeName 实际上是一个键 - 如果您 CMD+单击它,XCode 将带您到它的定义是:

UIKIT_EXTERN NSString * const NSParagraphStyleAttributeName NS_AVAILABLE(10_0, 6_0); // NSParagraphStyle, default defaultParagraphStyle

通过使用系统定义的属性键,系统实际上可以理解并将它们应用到您的字符串中。