UITextview typingAttributes不工作

我有UITextView,我想将它的行高设置为50.0f,所以我使用了typingAttributes,但没有任何工作,我的代码像这样在ViewDidAppear方法

UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 300, 300)]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.minimumLineHeight = 50.0f; paragraphStyle.lineHeightMultiple = 50.0f; paragraphStyle.maximumLineHeight = 50.0f; NSDictionary *textViewAttributeDic = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; textView.typingAttributes = textViewAttributeDic; 

文字不受影响设置typingAttributes,我试图改变颜色和字体使用typingAttributes但没有作品

我已经阅读了所有的堆栈答案和文档

我做错了:(

更新:我甚至尝试过

 UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 300, 300)]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.minimumLineHeight = 50.0f; paragraphStyle.lineHeightMultiple = 50.0f; paragraphStyle.maximumLineHeight = 50.0f; NSDictionary *textViewAttributeDic = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; textView.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:textViewAttributeDic]; 

当我尝试

 textView.attributedText = [[NSAttributedString alloc] initWithString:@"blahblah" attributes:textViewAttributeDic]; 

它的工作,但我需要空的textView没有空格或'胡说'字符

文档明确指出, typingAttributes是用于文本字段的编辑模式。

typingAttributes

要应用于由用户input的新文本的属性。

…如果文本字段不处于编辑模式,则此属性包含值nil。 同样,除非文本字段当前处于编辑模式,否则不能为该属性赋值。

相反,您应该分配attributedText text而不是text属性。 指定属性的机制是通过您分配的NSAttributedString

您可以在IB中使用临时文本在文本视图中configuration段落样式,并设置所有必需的属性。 然后,在启动时清除文本视图textView.text = nil 。 文本属性应保持不变。

在这里输入图像说明

在ios6我解决了这个问题,在我写的textView委托:

 - (void)textViewDidChange:(UITextView *)textView{ // 1st save current selected range ... we gonna use this value in 5th step NSRange textViewCurrentRange = textView.selectedRange; // 2nd disable scrolling in textview [textView setScrollEnabled:NO]; // 3rd set the new enterd text as attributed string to textview [textView setAttributedText:[[NSAttributedString alloc]initWithString:textView.text attributes:self.textAttributes]]; // 4th enable scrolling [textView setScrollEnabled:YES]; // 5th re set selected range so text inidicator will get back to it's place textView.selectedRange = textViewCurrentRange; } 

以编程方式设置attributedText typingAttributes attributedText重置typingAttributes attributedText 。 设置typingAttributes最后。

这里有一个问题 – 正如其他答案中提到的那样, UITextField必须处于编辑模式才能工作。 如果您正在模拟器中运行,并且键盘被隐藏(cmd + k),则如果使用计算机的键盘进行键入,则文本字段处于编辑模式。 确保模拟器的键盘显示。