UILabel左右对齐

时间:2011-09-11 13:13:43

标签: iphone ios cocoa-touch uilabel text-justify

我有UILabel(可可触摸框架),我想左右对齐它的文本。 因此,它将拉伸内部文本。

实施例: 就好像我有这个文字“虽然节省了实际制造和运输成本”,它看起来如下:

"While the saved"
"c o s t s   o f"
"p h y s i c a l"
 "manufacturing"
"a n d  shipping"

你可以看到左右对齐......

我怎么能实现那个???

非常感谢

  • 对不起,我不得不提出双重问题来发布问题。

8 个答案:

答案 0 :(得分:9)

您应该使用我的OHAttributedLabel课程。

它包含显示NSAttributedString所需的一切,包括证明左,中,右... 和对齐,并且使用起来非常简单。

你可以找到它here on 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常量以进行对齐。此类常量在Apple的SDK中不存在)


[编辑] iOS6 SDK

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

答案 1 :(得分:4)

使用UIWebView可能很慢,所以如果这是一个问题,CoreText就是这样的。

以下是一些使用核心文本在视图上显示属性字符串的代码。它有点像UILabel。我已经留下了一些其他段落格式选项来说明如何设置其他段落属性并将属性字符串设置为粗体。请记住,您需要添加CoreText框架,否则会出现构建错误。

此代码未完全证明最后一行。不确定你是否可以在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];

答案 2 :(得分: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;

答案 3 :(得分: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;

答案 4 :(得分: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;

答案 5 :(得分:1)

这就是所谓的“完全对齐”,但UILabel系统不支持它(只有“对齐” - 左,右和中)。如果你想要这个,你必须自己编写代码,用CoreText或类似的东西构建一个控件。

答案 6 :(得分:0)

同意这只能通过一些好的自定义编码来完成;我认为这将是一些非常沉重的东西。在你进入之前;这取决于你的要求;请考虑使用UIWebView,我认为您可以使用HTMLCSS编码更自由地管理文字样式和对齐。

答案 7 :(得分:-2)

以下作为快速修复,但请注意,除了黑色纯文本之外,您还需要一些样式或CSS。

(来自:Justified Alignment in UITextView - iPhone

  

我找到了一个有效的解决方案。首先,您需要更改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];