UILabel 左对齐和右对齐

发布于 2024-12-03 18:28:22 字数 328 浏览 1 评论 0原文

我有 UILabel (可可触摸框架),我想左右对齐其文本。 结果它会拉伸里面的文本。

例子: 就像如果我有这样的文本“虽然节省了物理制造和运输的成本”,它会如下所示:

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

正如您所看到的左对齐和右对齐......

我怎样才能实现这一点???

非常感谢

  • ,很抱歉我不得不使用双引号来发布问题。

i have UILabel (cocoa touch framework) and i want to right and left justify its text.
as a consequence it will stretch the text inside.

Example:
like if i had this text "While the saved costs of physical manufacturing and shipping" it would appear like the following:

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

as you can see left and right justification...

how can i achieve that ???

many thanks

  • i'm sorry i had to put the double qoutations to post the question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

夏了南城 2024-12-10 18:28:22

你应该使用我的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 常量匹配以进行对齐。此常量在 Apple 的 SDK 中不存在)


[编辑] iOS6 SDK

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

You should use my OHAttributedLabel class.

It has everything needed to display an NSAttributedString, including justifying left, center, right… and justified, and is really simple to use.

You can find it here on github. See the sample code provided that also shows how to change text justification.

// 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!

(Note: UITextAlignmentJustify is a constant defined in OHAttributedLabel headers that matches corresponding CoreText constant for justify alignment. This constant does not exists in Apple's SDK)


[EDIT] iOS6 SDK

Since iOS6 SDK, the UITextAlignmentJustify does not work anymore and generate a crash at runtime. Now you should set the text alignment of your NSAttributedString itself instead of using the textAlignment property of the label.

使用 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), ¶graphSpacing},
        { kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(CGFloat), ¶graphSpacingBefore},
    }; 

    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];

Using UIWebView can be slow, so if that's an issue CoreText is the way to go.

Here's some code that uses core text to display an attributed string on a view. It indents a bit like UILabel. I've left some other paragraph formatting options in to illustrate how you can set other paragraph properties and also set the attributed string to bold. Remember you'll need to add the CoreText framework otherwise you'll get build errors.

This code doesn't full justify the last line. Not sure you can get this for free in CoreText.

the .h file

//
//  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

And the .m file

//
//  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), ¶graphSpacing},
        { kCTParagraphStyleSpecifierParagraphSpacingBefore, sizeof(CGFloat), ¶graphSpacingBefore},
    }; 

    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

And to put to use, something like this:

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];
东京女 2024-12-10 18:28:22

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;

Its very easy after the release of IOS 6.
Use this

//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;
腹黑女流氓 2024-12-10 18:28:22

从 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;

From iOS 6 you can use NSMutableAttributedString for this,

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;
遮了一弯 2024-12-10 18:28:22

完美的解决方案是使用 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;

The perfect solution is to used 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;
沉睡月亮 2024-12-10 18:28:22

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

This is so called "full justification", but isn't supported by the UILabel system (which only has "alignments" - left, right and centre). If you want this, you'll have to code it up yourself, building a control with CoreText or similar.

诗笺 2024-12-10 18:28:22

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

Agree that this can only be done with a good bit of custom coding; which I would think will be some pretty heavy stuff. Before you get into that; and this is depending on your requirement; do consider having a UIWebView where I imagine you would be able to manage text styles and alignments with a bit more freedom using some HTML and CSS coding.

疏忽 2024-12-10 18:28:22

以下内容可作为快速修复,但请注意,对于黑色纯文本以外的任何内容,您将需要一些样式或 CSS。

(来自: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];

The following works as a quick fix, but note that for anything more than black plain text you'll need some styling or css.

(From: Justified Alignment in UITextView - iPhone)

I have come to a solution that works. First of all, you will need to change your UITextView and use a UIWebView instead.

    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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文