如何在iOS 7中设置UITextView中属性文本的颜色和对齐方式?

34

我的文本视图在 iOS 6 中的格式良好,但在 iOS 7 中不再正常工作。我知道 Text Kit 大部分底层技术已经改变了。这变得非常令人困惑,希望有人可以通过帮我解决这个简单的问题来帮助我搞清楚一些事情。

我的静态 UITextView 最初为其 textColortextAlignment 属性分配了值。然后我创建了一个 NSMutableAttributedString,为它分配了属性,然后将其赋值给 textView 的 attributedText 属性。在 iOS 7 中,对齐和颜色不再生效。

我该如何解决这个问题?如果这些属性不起作用,那么它们还存在的意义是什么?下面是 textView 的创建:

UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];

NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSParagraphStyleAttributeName value:font range:NSMakeRange(0, title.length)];
titleView.attributedText = title;

[self.view addSubview:titleView];
1个回答

67

奇怪的是,UILabel 的属性被考虑在内,但是对于 UITextView 却不是。

为什么不像处理字体一样,给属性字符串添加颜色和对齐方式的属性呢?

就像这样:

NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];

//add color
[title addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, title.length)];

//add alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[title addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, title.length)];

titleView.attributedText = title;

编辑:先分配文本,然后更改属性,这样就可以正常工作。

UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];

//create attributed string and change font
NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];

//assign text first, then customize properties
titleView.attributedText = title;
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];

当我这样做时,NSFontAttributeName属性似乎不再生效。它可以居中,颜色也没问题,但字体大小似乎是系统大小。我尝试先分配所有其他属性,最后再应用字体属性,但奇怪的是,应用程序会崩溃,并显示“终止应用程序,因为未捕获的异常'NSInvalidArgumentException',原因:'-[UICTFont textBlocks]:向实例0x8b1d1c0发送了无法识别的选择器'”。 - Joe
我想你指的是第二种选择(先分配文本,然后修改属性),但在那个例子中,我没有包括字体定制,我将修改它以包含完整的示例。 - jlhuertas
这两个代码示例对我来说产生了相同的结果。因此,似乎不需要分配UITextView的属性。你放它们进去有什么原因吗? - Joe
是的,这两个示例应该产生相同的结果。我只是添加了第二种方法(自定义UITextView的属性),因为你问为什么它们在你的示例中没有被考虑到。在我看来,我认为我的第一个示例更清晰易懂(仅使用属性字符串属性),而不是混合属性和UITextView属性。 - jlhuertas
哦,好的。你没有遇到我在第一条评论中描述的字体错误吗? - Joe
感谢您提供如此精彩的示例。 - John

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