如何将文本添加到活动的 UITextField
How to add text to an active UITextField
我有几个 UITextField
和一个 UIButton
。如果我点击 UIButton
,我想在活动 UITextField
中放置一些静态文本。
所以像这样:
@IBAction func buttonEen(sender: UIButton) {
'active textField'.text = "static text"
}
但是我如何确定哪个 UITextField
是活跃的 UITextField
以及如何到达它?
要在最后一个活动的 UITextField 中写入文本,您必须让您的 UIViewController
成为 UITextField
的代表
例如:
class ViewController: UIViewController, UITextFieldDelegate
声明一个activeField
变量
例如:
var activeField: UITextField?
然后实施 textFieldDidBeginEditing
例如:
func textFieldDidBeginEditing(textField: UITextField)
{
activeField = textField
}
所以你的按钮功能将类似于
@IBAction func buttonEen(sender: UIButton) {
if activeField
{
activeField.text = "static text"
}
}
首先您需要创建您的文本字段委托(可能在 'ViewDidLoad()' 中):
activeTxtField.delegate = self
然后需要实现textField委托函数:
extension 'YourVC': UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == activeTxtField {
// Do whatever you want
// e.g set textField text to "static text"
}
}
}
我有几个 UITextField
和一个 UIButton
。如果我点击 UIButton
,我想在活动 UITextField
中放置一些静态文本。
所以像这样:
@IBAction func buttonEen(sender: UIButton) {
'active textField'.text = "static text"
}
但是我如何确定哪个 UITextField
是活跃的 UITextField
以及如何到达它?
要在最后一个活动的 UITextField 中写入文本,您必须让您的 UIViewController
成为 UITextField
例如:
class ViewController: UIViewController, UITextFieldDelegate
声明一个activeField
变量
例如:
var activeField: UITextField?
然后实施 textFieldDidBeginEditing
例如:
func textFieldDidBeginEditing(textField: UITextField)
{
activeField = textField
}
所以你的按钮功能将类似于
@IBAction func buttonEen(sender: UIButton) {
if activeField
{
activeField.text = "static text"
}
}
首先您需要创建您的文本字段委托(可能在 'ViewDidLoad()' 中):
activeTxtField.delegate = self
然后需要实现textField委托函数:
extension 'YourVC': UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == activeTxtField {
// Do whatever you want
// e.g set textField text to "static text"
}
}
}