如何在UILabel中进行2次对齐

时间:2015-04-06 12:34:49

标签: ios uilabel nsattributedstring core-text nsparagraphstyle

我正在尝试创建一个UILabel,其中一些文本与右边对齐,一些文本与左边对齐。它类似于带有小箭头的UITableViewCell

enter image description here

我试图用NSAttributedString来做,但无法弄清楚解决这个问题的正确方法是什么。

以下是一些无效的代码。它与右边对齐。

NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:@"Label >"];

        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSTextAlignmentLeft;

        [att addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, @"Label".length)];

        NSMutableParagraphStyle *rightParagraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSTextAlignmentRight;
        [att addAttribute:NSParagraphStyleAttributeName value:rightParagraph range:NSMakeRange(5, 1)];

3 个答案:

答案 0 :(得分:0)

您可以使用NSAttributedString来满足您的要求,但使用两个UILabel会更好更清洁。

答案 1 :(得分:0)

我之前使用该代码做过,希望它也适合你。

NSString* alphaString = @“some text”;

NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentLeft;

NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] 
                                               initWithString:alphaString 
                                               attributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                               [UIFont fontWithName:@"HelveticaNeue" size:13],      NSFontAttributeName, 
    paragraphStyle, NSParagraphStyleAttributeName, nil]];

NSString * betaString = @“some other text”;

NSMutableParagraphStyle* paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
paragraphStyle2.alignment = NSTextAlignmentRight;


[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:betaString attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:13], NSFontAttributeName, paragraphStyle2, NSParagraphStyleAttributeName, nil]]];

yourLabel.attributedText = attributedString;

答案 2 :(得分:0)

使用2个标签。将所需的TextAlignment属性分配给它们。设置标签文本值后,写下以下行:

[textLabel sizeToFit];

虽然标签的尺寸不同,但它会设置为最小尺寸。并将避免文本重叠。