ios 如何检查 UITextField 何时更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28394933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:44:35  来源:igfitidea点击:

How do I check when a UITextField changes?

iosswiftuitextfield

提问by Fawad Masud

I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChangeso far I have done this:

我正在尝试检查文本字段何时更改,也相当于用于 textView 的函数 -textViewDidChange到目前为止我已经这样做了:

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

Which kind of works, but the topRightButtonis enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?

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

回答by Fawad Masud

SWIFT

迅速

Swift 4.2

斯威夫特 4.2

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

and

@objc func textFieldDidChange(_ textField: UITextField) {

}

SWIFT 3 & swift 4.1

SWIFT 3 和 Swift 4.1

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

and

func textFieldDidChange(_ textField: UITextField) {

}

SWIFT 2.2

斯威夫特 2.2

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

and

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

OBJECTIVE-C

目标-C

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

and textFieldDidChange method is

和 textFieldDidChange 方法是

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

回答by rmooney

You can make this connection in interface builder.

您可以在界面生成器中进行此连接。

  1. In your storyboard, click the assistant editor at the top of the screen (two circles in the middle). Assistant editor selected

  2. Ctrl + Click on the textfield in interface builder.

  3. Drag from EditingChanged to inside your view controller class in the assistant view. Making connection

  4. Name your function ("textDidChange" for example) and click connect. Naming function

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

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

  3. 从 EditingChanged 拖动到助手视图中的视图控制器类内部。 建立联系

  4. 命名您的函数(例如“textDidChange”)并单击连接。 命名功能

回答by Robert

Swift 5.0

斯威夫特 5.0

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

and handle method:

和处理方法:

@objc func textFieldDidChange(_ textField: UITextField) {

}

Swift 4.0

斯威夫特 4.0

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

and handle method:

和处理方法:

@objc func textFieldDidChange(_ textField: UITextField) {

}

Swift 3.0

斯威夫特 3.0

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

and handle method:

和处理方法:

func textFieldDidChange(textField: UITextField) { 

}

回答by Vinzzz

The way I've handled it so far: in UITextFieldDelegate

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

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 version

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
}

回答by Alessandro Mattiuzzi

Swift 3

斯威夫特 3

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

回答by aviran

Swift 3.0.1+(Some of the other swift 3.0 answers are not up to date)

Swift 3.0.1+(其他一些Swift3.0 答案不是最新的)

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

func textFieldDidChange(_ textField: UITextField) {

}

回答by radthemad4

textField(_:shouldChangeCharactersIn:replacementString:)worked for me in Xcode 8, Swift 3 if you want to check every single keypress.

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
}

回答by drewster

Swift 4

斯威夫特 4

Conform to UITextFieldDelegate.

符合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
}

回答by Abubakr Dar

You can use this delegate method from UITextFieldDelegate. It fires with every character change.

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

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

However THIS ONLY FIRES BEFOREa change is made (indeed, a change is only made if you do return true from here).

但是,这仅在进行更改之前触发(实际上,只有在您从此处返回 true 时才会进行更改)。

回答by marlonpya

Maybe use RxSwift ?

也许使用 RxSwift ?

need

需要

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

add imports obviously

明显添加进口

import RxSwift
import RxCocoa

So u have a textfield : UITextField

所以你有一个 textfield : UITextField

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

U have other 3 methods..

你还有其他3种方法..

  1. onError
  2. onCompleted
  3. onDisposed
  4. onNext
  1. 出错时
  2. 已完成
  3. 已处理
  4. 下一个