【发布时间】:2021-07-06 08:38:32
【问题描述】:
我是 swift 的新手,我正在尝试将我的背景颜色设置为用户在 UI 文本字段中输入的颜色。有没有办法做到这一点?
【问题讨论】:
-
预期输入是什么?例如“00AEEF”还是“浅蓝色”?
-
@aheze 红色或绿色
标签: swift input colors background uitextfield
我是 swift 的新手,我正在尝试将我的背景颜色设置为用户在 UI 文本字段中输入的颜色。有没有办法做到这一点?
【问题讨论】:
标签: swift input colors background uitextfield
我建议听UITextFieldDelegate 方法,而不是为textFieldDidChange 添加一个目标,只要文本字段中的文本发生变化(即使只添加一个字符)就会调用它。
textFieldShouldReturn(_:) 委托方法似乎适合您的目的 - 当按下 Return 键时会调用它。
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self /// set the delegate
}
}
extension ViewController: UITextFieldDelegate {
/// one of many UITextField delegate methods: see here for more https://developer.apple.com/documentation/uikit/uitextfielddelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField.text?.lowercased() {
case "red":
view.backgroundColor = UIColor.red
case "green":
view.backgroundColor = UIColor.green
default:
view.backgroundColor = UIColor.white /// default if entered text was not Red or Green
}
return true /// allow the return button to be pressed
}
}
结果:
【讨论】:
通过将以下代码添加到 ViewController 的 viewDidLoad() 来订阅 textField 中的更改:
override func viewDidLoad(){
//Subscribe to changes in the textField
textfield.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)
}
您可以使用textField.text 获取 UITextField 的名称,并将其传递给 UIColor 的初始化程序,并使用它来设置视图背景的颜色,如下所示:
@objc func textFieldDidChange(_ textField: UITextField) {
if let text = textField.text{
self.view.backgroundColor = UIColor(named: text) ?? UIColor(named: "white")
}
}
【讨论】: