目标C,排列和着色标签?

时间:2014-05-03 20:15:30

标签: ios objective-c cocoa-touch uilabel

我正在尝试在同一行中对应用程序中的标签进行排列和着色。但我不知道我该怎么做。假设我有一系列标签,都有不同的颜色。

NSArray *MyArray = @[
                     @"#BlackSabbath", // red
                     @"#Dio", // blue
                     @"#TenaciousD" // yellow
                     ];

我想把它们排成一行。嗯,我知道我可以创建一个单独的UILabel并将它们全部作为NSString粘贴在那里。然而,我将如何着色它们呢?如果这是HTML,我可以使用span标签,但我不相信Objective C中的等价物。

我知道我也可以将一堆UILabel排成一行并单独着色,但我不知道如何根据文字大小调整宽度,因为某些标签的文字长度会比其他人长。

2 个答案:

答案 0 :(得分:1)

类似的东西,这是来自我的一些代码,你应该稍微改变它,但我认为你可以弄清楚大局。我用它来打印背景颜色的名字,用逗号分隔(没有背景),比如UILabel中的facebook标记:

NSMutableAttributedString * hashtagAttributedString = [[NSMutableAttributedString alloc]init];
    [hashtagAttributedString beginEditing];
    NSAttributedString * comma = [[NSAttributedString alloc]initWithString:@","];
    //Iterate trough array of users
    for (AFUser * user in self.selectedUsers) { 
        NSAttributedString *myString = [[NSAttributedString alloc]initWithString: user.userSurnameAndName attributes:
                                        @{ NSBackgroundColorAttributeName : [UIColor colorWithRed:0.525490 green:0.803922 blue:0.301961 alpha:1.000000] ,
                                           NSFontAttributeName : self.taggedUsersLabel.font
                                           }];

        [hashtagAttributedString appendAttributedString:myString];
        if (self.selectedUsers.count > 1) {
            [hashtagAttributedString appendAttributedString:comma];
        }
    }
    [hashtagAttributedString endEditing];
    self.taggedUsersLabel.attributedText = hashtagAttributedString;

答案 1 :(得分:1)

建议

如果您曾经使用过HTML,则可以使用此库来自定义标签:

示例代码

一个简单的方法

NSString *theMarkup = @"<b>Hello world</b>";
[theLabel setMarkup:theMarkup];

创建自定义样式

// Here's the markup we want to put into our UILabel. Note the custom <username> tag
NSString *theMarkup = [NSString stringWithFormat:@"<username>%@</username> %@", theUsername, theBody];

NSError *theError = NULL;

// Create a transformer and set up the standard styling (that part is optional)
CMarkupTransformer *theTransformer = [[CMarkupTransformer alloc] init];
[theTransformer addStandardStyles];

// Create custom attributes for our new "username" tag
NSDictionary *theFormatDictionary = @{
    NSForegroundColorAttributeName: [UIColor blueColor],
    kMarkupFontNameMetaAttributeName: @"Helvetica",
    };
[self addFormatDictionary:theFormatDictionary forTag:@"username"];

// Transform the markup into a NSAttributedString
NSAttributedString *theAttributedString = [theTransformer transformMarkup:inMarkup baseFont:self.font error:&theError];

// Give the attributed string to the CCoreTextLabel.
self.label.attributedString = theAttributedString;
相关问题