我有一个UITextView
,我需要检测用户在其中输入的颜色String
。然后,我需要将UITextField
中文本的颜色更改为用户键入的颜色。
例如:如果我在textField
中键入"红色",文本的颜色应更改为红色。
有谁知道这是怎么做到的?
谢谢!
首先,您需要创建String
到UIColor
的映射。
let colorMapping: [String: UIColor] = [
"green": .green,
"white": .white,
//etc...
]
首先将每种颜色的文本映射到其相应的UIColor
:
let colors: [String: UIColor] = [
// add any built-in colors
"red": .red,
"blue": .blue,
// custom colors too!
"goldenrod": UIColor(red: 218, green: 165, blue: 32)
// add all the colors you wish to detect
// ...
// ...
]
使包含文本字段的视图控制器符合UITextViewDelegate
并实现shouldChangeTextIn
函数(每当用户输入/删除字符时调用(:
class MyViewController: UIViewController, UITextFieldDelegate {
// ... other view controller code
func textField(_ textField: UITextField, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let currentText = textField.text {
// check if the text is in the `colors` dictionary
// and if so, apply the color to the `textColor`
if colors.keys.contains(currentText) {
textField.textColor = colors[currentText]
}
}
return true
}
// ... other view controller code
}
您可以使用以下委托方法检测文本字段中的文本
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
//Don't forgot to make user entered content to lowercaseString while checking with colorCollection
if colorCollection.keys.contains(textField.text.lowercaseString) {
textField.textColor = colorCollection[currentText] //If entered content match with any colour then it will change the text colour of textfield
}
return true
}
创建简单的颜色集合,如下所示
let colorCollection: [String: UIColor] = [
"blue": .blue,
"purple": .purple,
//your other coolers
]
所以假设你有文本字段和文本视图出口或以编程方式创建:-
let textField = UITextField()
let txtVw = UITextView()
//If enter some text inside textfield for instance red then get the value, compare it and set the text color on textview
if textField.text?.lowercased() == "red" {
txtVw.textColor = UIColor.red
}