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

时间:2013-10-12 22:33:15

标签: ios uitextview nsattributedstring textkit

我的textViews的格式在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 个答案:

答案 0 :(得分:65)

好奇,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];