2016-05-15 202 views
-1

如何通过在TextView中键入来更改颜色?在Swift TextView中更改打印颜色

例如,我输入黑色,然后按下颜色橙色按钮和更多橙色的打印文本,然后按下黑色按钮并打印黑色文本?

所研究的方法,可以将所有输入的文本或占位符等

+0

你需要改变输入文字的颜色吗?你试过什么了? – iYoung

+0

你看过“UITextView”的文档吗?您设置的一个明显属性定义了输入文本的属性。 – rmaddy

+0

@rmaddy我相信这些属性会改变字段中的所有文本?他似乎是在改变新文本并保持现有文本的格式之后。 –

回答

1

的颜色试试这个方法:

@IBAction func blackButtonClicked(sender: UIButton) { 
    let attributedText = textView.attributedText 

    textView.textColor = UIColor.blackColor() 
    textView.attributedText = attributedText 
} 

@IBAction func redButtonClicked(sender: UIButton) { 
    let attributedText = textView.attributedText 

    textView.textColor = UIColor.redColor() 
    textView.attributedText = attributedText 
} 

enter image description here

您还可以通过设置的typingAttributes财产实现这一textView,这似乎是一个更好的解决方案:

@IBAction func redButtonClicked() { 
    textView.typingAttributes[NSForegroundColorAttributeName] = UIColor.redColor() 
} 

@IBAction func blackButtonClicked() { 
    textView.typingAttributes[NSForegroundColorAttributeName] = UIColor.blackColor() 
} 
+1

谢谢你,ViktorSimkó! – SashDing

+0

@SashDing不客气!如果它解决了你的问题,你可以接受这个答案。 –

+0

这个美丽的代码决定了我的问题!谢谢! – SashDing