2013-02-01 211 views
-1

我具有其中文本被显示这样的文本视图:文本编辑

how are you? 

Fine 

现在,如果我设置为文本视图,那么相同的字体被显示为两行字体(疑问句和答案),但是我想要问题以一种字体显示并以其他字体回答。我怎样才能做到这一点?

我设置字体这样的:

textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 80, 300, 440)]; 
textView.layer.borderColor = [UIColor blackColor].CGColor; 
[textView setFont:[UIFont fontWithName:@"TimesNewRomanPS-ItalicMT" size:14]]; 
textView.layer.borderWidth = 1.0; 
    textView.autoresizesSubviews = YES; 
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
[self.view addSubview:textView]; 

在此先感谢!

+0

它看起来像相同的要求。 http://stackoverflow.com/questions/2183275/how-to-give-background-color-for-selected-text-in-text-view – Madhu

回答

4

UITextView class reference

在iOS 6中,后来,这个类支持通过 使用attributedText属性的多个文本样式。 (在 早期版本的iOS中不支持样式文本。)为此属性设置值会导致 文本视图使用属性 字符串中提供的样式信息。您仍然可以使用字体,textColor和textAlignment属性来设置样式属性,但这些属性适用于文本视图中文本的所有 。

该课程不支持多种文本样式。您指定的字体,颜色, 和文本对齐属性始终适用于文本视图的整个 内容。要在您的 应用程序中显示更复杂的样式,您需要使用UIWebView对象并使用HTML呈现您的 内容。

因此,您不能在iOS 5或更低版本的同一页上拥有两个,因为它不受支持。只需使用一个webview和一个HTML文件。对于iOS6,也许你可以尝试使用UITextView的attributedText属性。这是在iOS 6下可用。但从来没有尝试过。或者有2个不同的UITextView(它的丑陋,但多数民众赞成它是什么)。

+0

如果我走的,而不是UITextView中的UILabel,那我该怎么做这个? – user1845209

+0

你的代码的哪部分是静态的?问题是静态的吗?或回答静态?如果它们中的任何一个是静态的,那么你可以使用UILabel来代替它们。它们也更适合你的内存管理。 –

0

我猜你想创建一个聊天室的应用程序?

如果是这样,我建议让它成为一个UITableView。然后让不同的单元格匹配不同的样式。

0

您可以使用归因字符串来实现这一点,例如:

NSMutableAttributedString *para1 = [[NSMutableAttributedString alloc] initWithString:@"How are you?"]; 
NSMutableAttributedString *para2 = [[NSMutableAttributedString alloc] initWithString:@"\nFine"]; 
[para2 setAttributes:@{ NSForegroundColorAttributeName : [UIColor blueColor]} range:NSMakeRange(0, para2.length)]; 
[para1 insertAttributedString:para2 atIndex:para1.length]; 

self.textLabel.attributedText = para1; 

或用单属性串:

NSMutableAttributedString *para1 = [[NSMutableAttributedString alloc] initWithString:@"How are you?\nFine"]; 

// Get the range of the last line in the string 
__block NSRange range; 
[para1.mutableString enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { 
    range = [para1.mutableString rangeOfString:line]; 
}]; 

[para1 setAttributes:@{ NSForegroundColorAttributeName : [UIColor blueColor] } range:range]; 

self.textLabel.attributedText = para1; 

两个例子都导致:

Output

+0

如果我只有一个字符串中的文本说para1呢?实际上这个数据来自tableview的textLabel,它包含问题和答案。 – user1845209

+0

您可以使用单个属性字符串实现相同的结果,但必须使用方法:-addAttributes:range :.我会更新我的答案以显示两种方法。 –

+0

我假设你将要使用的字符串是自由格式的,所以我修改了我的答案,以查找字符串中最后一行的范围,并将蓝色属性应用到该行。让我知道你的想法。 –