NSMutableAttributedString添加不同的对齐方式 [英] NSMutableAttributedString add different alignments

查看:1440
本文介绍了NSMutableAttributedString添加不同的对齐方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在字符串的不同部分添加左对齐和右对齐?

Is it possible to add left and right alignments to different parts of the string?

我尝试将对齐属性添加到右侧部分:

I tried to add alignment attribute to the right part:

    NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
    [paragrahStyle setAlignment:NSTextAlignmentRight];
    [mutableAttributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:rangeOfDate];

但整个字符串与左边对齐。

But the whole string is aligned to the left.

推荐答案

在代码中执行的操作是设置段落样式(从\ n到\ n的文本),并且不能在文本中使用多个文本对齐方式。同款。我遇到了同样的问题并最终在iOS 6中使用了多个UILabel: - (

What you do in your code is to set the paragraph style (the text from \n to \n) and it is not possible to have multiple text alignments in the same paragraph. I had the same problem and ended up using multiple UILabels in iOS 6 :-(

然而,在iOS 7中,我注意到ParagraphStyle的TabStops。这实际上使它成为可能,但是我发现文档非常不合适。但是,我最终得到了它。你可以设置一个右对齐的TapStop,这会导致你的文本被渲染到你指定的停止的左边(直到那个空间被填满)。得到我的简单示例工作我必须添加至少一个属性,除了第一段 - 它可能只是一个明确的背景的UIColor: - )

However, in iOS 7 I noticed TabStops for ParagraphStyle. This actually makes it possible, but I find the documentation quite inadequate. However, I ended up getting it to work. You can set a right aligned TapStop, which causes your text to get rendered to the left of your specified stop (until that space is filled). In order to get my simple example to work I had to add at least one more attribute besides the paragraph one - it could have been just a clear UIColor for the background though :-)

以下是UIView中drawRect的一个简单示例:

The following is a simple example of drawRect in a UIView:

- (void)drawRect:(CGRect)rect
{
    NSString *str = @"to the left\tto the right\nleft again\tright again";
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:str];

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

    NSTextTab *t = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentRight location:rect.size.width options:nil];
    paragraph.tabStops = @[t];

    [att addAttribute:NSBackgroundColorAttributeName value:[UIColor magentaColor] range:NSMakeRange(0, @"to the left".length)];
    [att addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Trebuchet-BoldItalic" size:12.0] range:NSMakeRange(12, 5)];
    [att addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(str.length - 4, 2)];
    [att addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, str.length)];

    [att drawInRect:rect];
}

该代码将呈现以下内容:

That code will render the following:

这篇关于NSMutableAttributedString添加不同的对齐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆