UILabel两端对齐(左右对齐)

9
我有一个UILabel(Cocoa Touch框架),我想将其文本右对齐和左对齐。 因此,它会拉伸文本内部。
例如: 如果我有这个文本“While the saved costs of physical manufacturing and shipping”,它会显示如下:
"While the saved"
"c o s t s   o f"
"p h y s i c a l"
 "manufacturing"
"a n d  shipping"

如您所见,左右对齐...

我该怎么做才能实现它???

非常感谢

  • 很抱歉我不得不加上双引号以发布问题。

尝试这个...youLable.textAlignment = UITextAlignmentLeft。如果你已经做过了,那么请发布你编写的在标签上设置文本的代码。 - Mohammad
它不起作用。UITextAlignmentRight和UITextAlignmentCenter也无法起作用。 - M.Saleh
8个回答

9

你应该使用我的OHAttributedLabel类。

它拥有显示NSAttributedString所需的一切,包括左对齐、居中、右对齐和两端对齐,并且使用起来非常简单。

你可以在这里的github页面找到它。查看提供的示例代码,其中还展示了如何更改文本对齐方式。

// suppose that label is an IBOutlet to an OHAttributedLabel (subclass oh UILabel)
label.textAlignment = UITextAlignmentJustify; // and that's all, OHAttributedLabel does everything needed for you!

(注意:UITextAlignmentJustify是OHAttributedLabel头文件中定义的常量,它匹配文本对齐方式的CoreText常量。这个常量在苹果的SDK中不存在。)

[编辑] iOS6 SDK

自从iOS6 SDK之后,UITextAlignmentJustify不再起作用,并且会在运行时崩溃。现在,您应该设置NSAttributedString的文本对齐方式,而不是使用标签的textAlignment属性。

它只能与IBOutlets一起使用吗?我不能在代码中创建的标签上使用它吗? - Andrey Chernukha
1
当然可以!使用IB创建的标签(并使用IBOutlet连接到变量)或通过代码创建的标签之间没有区别。 - AliSoftware
使用"NSTextAlignmentLeft"代替"UITextAlignemtnLeft"似乎可行且未被废弃。 - powerj1984
对于iOS6+,我建议放弃使用OHAttributedLabel,转而使用原生的UILabelNSAttributedString - Cœur
完全同意 @Cœur(顺便说一句,OHAttributedLabel 已经过时了)。对于那些感兴趣的人,我现在在我的新的 OHAttributedStringAdditions pod 中提取了所有有用的 NSAttributedString 类别,它可以帮助您更轻松地操作 NS(Mutable)AttributedString 对象(并且与 iOS6+ 和 TextKit 兼容)。 - AliSoftware
显示剩余7条评论

4
使用UIWebView可能会很慢,所以如果这是个问题,那么CoreText是一种更好的选择。
以下是使用CoreText在视图上显示带属性字符串的代码。它有点像UILabel缩进。我留下了一些其他段落格式选项,以说明如何设置其他段落属性并将属性字符串设置为粗体。请记住,您需要添加CoreText框架,否则您将获得构建错误。
这段代码不会完全调整最后一行。不确定您是否可以免费获取此功能。
.h文件
//
//  SmartLabel.h
//

#import <UIKit/UIKit.h>
#import <CoreText/CoreText.h> // needed for CTFontRef, CTFontCreateWithName

@interface SmartLabel : UIView
{
    NSMutableAttributedString* _pgSmartString;
}

@property (nonatomic, retain) NSMutableAttributedString* smartString;

- (void) setText: (NSString*) string;
- (void) formatString;

@end

文件是 .m 文件

//
//  SmartLabel.m
//

#import "SmartLabel.h"

@implementation SmartLabel

@synthesize smartString = _pgSmartString;

- (void)dealloc
{
    [_pgSmartString release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame;
{
    if ((self = [super initWithFrame:frame]))
    {
        [self setBackgroundColor: [UIColor clearColor]];
    }
    return self;
}


- (void)drawRect:(CGRect)rect
{
    CGContextRef graphicsContext = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(graphicsContext, CGAffineTransformIdentity);

    // turns things right way up
    CGContextTranslateCTM(graphicsContext, 0, self.bounds.size.height);
    CGContextScaleCTM(graphicsContext, 1.0, -1.0);

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)[self smartString]);

    CGRect bounds = [self bounds];
    bounds.origin.x = bounds.origin.x + 8;
    bounds.size.width = bounds.size.width - 16;

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, bounds);

    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [[self smartString] length]), path, NULL);
    CFRelease(path);

    CTFrameDraw(frame, graphicsContext); 
    CFRelease(frame);
    CFRelease(framesetter);
}


- (void) setText: (NSString*) string;
{
    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    [self setSmartString:attributedString];
    [attributedString release];
    [self formatString];
}


- (void) formatString;
{
    CTTextAlignment alignment = kCTJustifiedTextAlignment; // could put different alignments here

    CGFloat paragraphSpacing = 11.0;
    CGFloat paragraphSpacingBefore = 0.0;
    CGFloat firstLineHeadIndent = 0.0;
    CGFloat headIndent = 0.0;

    CTParagraphStyleSetting altSettings[] = 
    {
        { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &alignment},
        { kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(CGFloat), &firstLineHeadIndent},
        { kCTParagraphStyleSpecifierHeadIndent, sizeof(CGFloat), &headIndent},
        { kCTParagraphStyleSpecifierParagraphSpacing, sizeof(CGFloat), &paragraphSpacing},
        { kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(CGFloat), &paragraphSpacingBefore},
    }; 

    CTParagraphStyleRef style;
    style = CTParagraphStyleCreate( altSettings, sizeof(altSettings) / sizeof(CTParagraphStyleSetting) );

    if ( style == NULL )
    {
        NSLog(@"***  WARNING *** Unable To Create CTParagraphStyle in apply paragraph formatting" );
        return;
    }

    [[self smartString] addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:(NSObject*)style,(NSString*) kCTParagraphStyleAttributeName, nil] range:NSMakeRange(0,[[self smartString] length])];

    CFRelease(style);

    UIFont* boldFont = [UIFont boldSystemFontOfSize:12.0];

    CTFontRef boldCoreTextFontReference =  CTFontCreateWithName ((CFStringRef)[boldFont fontName],[boldFont pointSize], NULL);
    [[self smartString] addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:(NSObject*)boldCoreTextFontReference,(NSString*) kCTFontAttributeName, nil] range:NSMakeRange(0,[[self smartString] length])];
}

@end

并且为了投入使用,可以像这样:

SmartLabel* smartLabel = [[SmartLabel alloc] initWithFrame:CGRectMake(20, 120, 90, 140.0)];
[[self window] addSubview:smartLabel];
[smartLabel setText:@"While the saved costs of physical manufacturing and shipping"];
[smartLabel release];

请问您如何使用这个文件设置内容的文本颜色? - Maulik Kundaliya

2
完美的解决方案是使用NSMutableParagraphStyle
NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
        paragraphStyles.alignment = NSTextAlignmentJustified;      //justified text
        paragraphStyles.firstLineHeadIndent = 1.0;
        NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyles};
        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: YourString attributes: attributes];
        YourLabel.attributedText = attributedString;

2

iOS 6发布后,这非常容易。

使用此方法:

//build a style for justification

NSMutableParagraphStyle *stringStyle=[[NSMutableParagraphStyle alloc]init];

[stringStyle setAlignment:NSTextAlignmentJustified];

//build a string with the particular paragraph style

NSMutableAttributedString* yourString=[[NSMutableAttributedString alloc]init];

[yourString addAttribute:NSParagraphStyleAttributeName value:stringStyle range:NSMakeRange(0, [yourString length])];

//and here you go

UILabel *yourLabel;

yourlabel.attributedText=yourString;

在iOS 6中正常工作,但在iOS 7中无法工作:====== NSMutableParagraphStyle stringStyle = [[NSMutableParagraphStyle alloc]init]; [stringStyle setAlignment:NSTextAlignmentJustified]; NSMutableAttributedString descString = [[NSMutableAttributedString alloc]initWithString:cell.lblDetailDesc.text]; [descString addAttribute:NSParagraphStyleAttributeName value:stringStyle range:NSMakeRange(0, [descString length])]; cell.lblDetailDesc.attributedText = descString; - Ram S

2

iOS 6之后,您可以使用NSMutableAttributedString来实现此功能。

NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithData:[@"Your String value" dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];
NSRange rangeOfTitle = NSMakeRange(0,[attrStr length]);
[attrStr addAttribute: NSFontAttributeName value:[UIFont fontWithName:@"Calibri" size:19.0]range:rangeOfTitle];
 myLabel.attributedText = attrStr;
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:10]; 
style.lineBreakMode = NSLineBreakByWordWrapping;
style.alignment = NSTextAlignmentJustified;
[attrStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, myLabel.text.length)];
myLabel.attributedText = attrStr;

太好了!只需要用HTML元素 <br> 替换掉新行符 "/n" 即可。 - Jim75

1
这是所谓的“全对齐”,但它不被UILabel系统支持(该系统只有“对齐”——左、右和中心)。如果您想要这个效果,您需要自己编写代码,使用CoreText或类似的工具创建一个控件。

可能有,但我不知道。 - Adam Wright

0
同意这只能通过大量的自定义编码来完成;我认为这将是一些相当复杂的东西。在你开始之前,这取决于你的要求,请考虑使用UIWebView,在那里你可以使用一些HTMLCSS编码更自由地管理文本样式和对齐方式。

实际上,我之前使用的是UIWebView,但由于它加载较慢,所以决定将其改为UILabel。 - M.Saleh

-2
以下是一个快速解决方案,但请注意,如果需要除黑色纯文本之外的任何样式或CSS,则需要进行一些样式处理。
(来自:iPhone上UITextView的对齐方式

我已经找到了一个可行的解决方案。首先,您需要更改UITextView并改用UIWebView。

    Details.h

    @interface Details : UIViewController {
    IBOutlet UIWebView *descripcion;
    }

    @property (nonatomic, retain) UITextView *descripcion;

Then, load your UIWebView as follows:

    Details.m

    [descripcion loadHTMLString:[NSString stringWithFormat:@"<div align='justify'>%@<div>",YOUR_TEXT] baseURL:nil];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接