如何检查UITextField何时更改?

时间:2015-02-08 14:16:24

标签: ios swift uitextfield

我正在尝试检查文本字段何时更改,相当于textView使用的函数 - textViewDidChange到目前为止我已经完成了此操作:

  func textFieldDidBeginEditing(textField: UITextField) {
        if self.status.text == "" && self.username.text == "" {
            self.topRightButton.enabled = false
        } else {   
            self.topRightButton.enabled = true
        }
    }

哪种方式有效,但只要按下文本字段就会启用topRightButton,我希望只有在实际输入文字时才能启用它?

20 个答案:

答案 0 :(得分:614)

<强> SWIFT

textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)

然后你可以打电话给你的功能!

func textFieldDidChange(textField: UITextField) {
    //your code
}

SWIFT 2.2

textField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

func textFieldDidChange(textField: UITextField) {
    //your code
}

SWIFT 3&amp; swift 4.1

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

func textFieldDidChange(_ textField: UITextField) {

}

Swift 4

@objc func textFieldDidChange(_ textField: UITextField) {

}

<强>目的-C

[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

和textFieldDidChange方法是

-(void)textFieldDidChange :(UITextField *) textField{
    //your code
}

答案 1 :(得分:107)

您可以在界面构建器中建立此连接。

  1. 在故事板中,单击屏幕顶部的助理编辑器(中间的两个圆圈)。 Assistant editor selected

  2. Ctrl +单击界面构建器中的文本字段。

  3. 从EditingChanged拖动到助手视图中的视图控制器类内部。 Making connection

  4. 为您的函数命名(例如“textDidChange”),然后单击“连接”。 Naming function

答案 2 :(得分:45)

Swift 3.0

textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)

和处理方法:

func textFieldDidChange(textField: UITextField) { 

}

Swift 4.0

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControlEvents.editingChanged)

和处理方法:

@objc func textFieldDidChange(_ textField: UITextField) {

}

Swift 5.0

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControl.Event.editingChanged)

和处理方法:

@objc func textFieldDidChange(_ textField: UITextField) {

}

答案 3 :(得分:25)

到目前为止我处理它的方式:UITextViewDelegate

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    // text hasn't changed yet, you have to compute the text AFTER the edit yourself
    let updatedString = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range, withString: string)

    // do whatever you need with this updated string (your code)


    // always return true so that changes propagate
    return true
}

Swift4版

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
    return true
}

答案 4 :(得分:14)

Swift 3

 textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(sender:)), for: UIControlEvents.editingChanged)

答案 5 :(得分:7)

Swift 3.0.1 + (其他一些swift 3.0答案不是最新的)

textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
                          for: UIControlEvents.editingChanged)

func textFieldDidChange(_ textField: UITextField) {

}

答案 6 :(得分:5)

如果你想检查每一个按键,

textField(_:shouldChangeCharactersIn:replacementString:)在Xcode 8,Swift 3中为我工作。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Whatever code you want to run here.
    // Keep in mind that the textfield hasn't yet been updated,
    // so use 'string' instead of 'textField.text' if you want to
    // access the string the textfield will have after a user presses a key

    var statusText = self.status.text
    var usernameText = self.username.text

    switch textField{
    case self.status:
        statusText = string
    case self.username:
        usernameText = string
    default:
        break
    }

    if statusText == "" && usernameText == "" {
        self.topRightButton.enabled = false
    } else {   
        self.topRightButton.enabled = true
    }

    //Return false if you don't want the textfield to be updated
    return true
}

答案 7 :(得分:5)

Swift 4

符合 UITextFieldDelegate

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // figure out what the new string will be after the pending edit
    let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)

    // Do whatever you want here


    // Return true so that the change happens
    return true
}

答案 8 :(得分:4)

您可以使用UITextFieldDelegate中的此委托方法。它随着每一个角色的变化而激发。

(Objective C) textField:shouldChangeCharactersInRange:replacementString:
(Swift) textField(_:shouldChangeCharactersInRange:replacementString:)

然而,只有在之前进行了更改(事实上,只有在您从此处返回true时才会进行更改)。

答案 9 :(得分:3)

iOS13 +上现在有一个UITextField委托方法

optional func textFieldDidChangeSelection(_ textField: UITextField)

答案 10 :(得分:2)

也许使用RxSwift?

需要

pod 'RxSwift',    '~> 3.0'
pod 'RxCocoa',    '~> 3.0'

明显添加导入

import RxSwift
import RxCocoa

所以你有textfield : UITextField

let observable: Observable<String?> = textField.rx.text.asObservable()
observable.subscribe(
            onNext: {(string: String?) in
                print(string!)
        })

你有其他3种方法..

  1. 的onError
  2. onCompleted
  3. onDisposed
  4. onNext

答案 11 :(得分:1)

Swift 4

textField.addTarget(self, action: #selector(textIsChanging), for: UIControlEvents.editingChanged)

@objc func textIsChanging(_ textField:UITextField) {

 print ("TextField is changing")

}

如果您想在用户完全输入后进行更改(一旦用户关闭键盘或按回车键即会调用它。)

textField.addTarget(self, action: #selector(textDidChange), for: UIControlEvents.editingDidEnd)

 @objc func textDidChange(_ textField:UITextField) {

       print ("TextField did changed") 
 }

答案 12 :(得分:1)

txf_Subject.addTarget(self, action:#selector(didChangeFirstText), for: .editingChanged)

@objc func didChangeText(textField:UITextField) {
    let str = textField.text
    if(str?.contains(" "))!{
        let newstr = str?.replacingOccurrences(of: " ", with: "")
        textField.text = newstr
    }
}

@objc func didChangeFirstText(textField:UITextField) {
    if(textField.text == " "){
        textField.text = ""
    }
}

答案 13 :(得分:1)

您应该按照以下步骤操作:

  1. 对文本字段进行Outlet引用
  2. 将AssignUITextFieldDelegate分配给控制器类
  3. 配置yourTextField.delegate
  4. 实施您需要的任何功能
  5. 示例代码:

    import UIKit
    
    class ViewController: UIViewController, UITextFieldDelegate {
    
        @IBOutlet var yourTextFiled : UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            yourTextFiled.delegate = self
        }
    
    
        func textFieldDidEndEditing(_ textField: UITextField) {
            // your code
        }
    
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            // your code
        }
    
        .
        .
        .
    }
    

答案 14 :(得分:0)

创建新的自定义类MaterialTextfield.swift

class MaterialTextfield: UITextField,UITextFieldDelegate {

var bottomBorder = UIView()
var shouldShowEditing = false

override func awakeFromNib() {

    // Setup Bottom-Border

    self.delegate = self
    self.translatesAutoresizingMaskIntoConstraints = false

    bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1) // Set Border-Color
    bottomBorder.translatesAutoresizingMaskIntoConstraints = false

    addSubview(bottomBorder)

    bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength

}
@IBInspectable var hasError: Bool = false {
    didSet {
        if (hasError) {
            bottomBorder.backgroundColor = UIColor.red//error color
        } else {
            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)//passive color
        }

    }
}
@IBInspectable var showEditing: Bool = false{
    didSet {
        if (showEditing) {
            bottomBorder.backgroundColor = UIColor(rgb: 0x56B5CA)//active color
        } else {
            bottomBorder.backgroundColor = UIColor(rgb: 0xE2DCD1)//passive color
        }

    }

}

func textFieldDidBeginEditing(_ textField: UITextField) {//listen to on edit event
    showEditing = !self.showEditing
}
func textFieldDidEndEditing(_ textField: UITextField) {//listen to on end edit event
    showEditing = !self.showEditing
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {//listen to return button event
    textField.resignFirstResponder() // return button will close keyboard
    return true
}

}

答案 15 :(得分:0)

Swift 4.2

将其写在viewDidLoad

// to detect if TextField changed
TextField.addTarget(self, action: #selector(textFieldDidChange(_:)),
                                   for: UIControl.Event.editingChanged)

在viewDidLoad外部写这个

@objc func textFieldDidChange(_ textField: UITextField) {
    // do something
}

您可以通过UIControl.Event.editingDidBegin或您要检测的内容来更改事件。

答案 16 :(得分:0)

只要您对SwiftUI解决方案感兴趣,它就对我有用:

 TextField("write your answer here...",
            text: Binding(
                     get: {
                        return self.query
                       },
                     set: { (newValue) in
                        self.fetch(query: newValue) // any action you need
                                return self.query = newValue
                      }
            )
  )

我不得不说这不是我的主意,我在以下博客中读过:SwiftUI binding: A very simple trick

答案 17 :(得分:0)

如果无法将addTarget绑定到UITextField,我建议您按照上面的建议将其中之一绑定,并在shouldChangeCharactersIn方法的末尾插入要执行的代码。

nameTextField.addTarget(self, action: #selector(RegistrationViewController.textFieldDidChange(_:)), for: .editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {
    if phoneNumberTextField.text!.count == 17 && nameTextField.text!.count > 0 {
        continueButtonOutlet.backgroundColor = UIColor(.green)
    } else {
        continueButtonOutlet.backgroundColor = .systemGray
    }
}

并在函数中的shouldChangeCharactersIn中调用。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let text = textField.text else {
        return true
    }
    let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String

    if phoneNumberTextField == textField {
        textField.text = lastText.format("+7(NNN)-NNN-NN-NN", oldString: text)
        textFieldDidChange(phoneNumberTextField)
        return false
    }
    return true
}

答案 18 :(得分:0)

这是使用 Swift 3 添加textField text change listener的方法:

将您的班级声明为UITextFieldDelegate

override func viewDidLoad() {
    super.viewDidLoad()

    textField.delegate = self

    textField.addTarget(self, action: #selector(UITextFieldDelegate.textFieldShouldEndEditing(_:)), for: UIControlEvents.editingChanged)
}

然后传统上只添加一个textFieldShouldEndEditing函数:

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { // do stuff
        return true 
}

答案 19 :(得分:-1)

swift 4

在viewDidLoad()中:

    //ADD BUTTON TO DISMISS KEYBOARD

    // Init a keyboard toolbar 
    let toolbar = UIView(frame: CGRect(x: 0, y: view.frame.size.height+44, width: view.frame.size.width, height: 44))
    toolbar.backgroundColor = UIColor.clear

    // Add done button
    let doneButt = UIButton(frame: CGRect(x: toolbar.frame.size.width - 60, y: 0, width: 44, height: 44))
    doneButt.setTitle("Done", for: .normal)
    doneButt.setTitleColor(MAIN_COLOR, for: .normal)
    doneButt.titleLabel?.font = UIFont(name: "Titillium-Semibold", size: 13)
    doneButt.addTarget(self, action: #selector(dismissKeyboard), for: .touchUpInside)
    toolbar.addSubview(doneButt)

    USDTextField.inputAccessoryView = toolbar

添加此功能:

    @objc func dismissKeyboard() {
      //Causes the view (or one of its embedded text fields) to resign the first responder status.
      view.endEditing(true)
    }