ios - 在用户输入有四个字符后,如何在 Swift 3 中调用准备方法?

标签 ios swift swift3 segue

我有以下方法:

@IBAction func postcodeTextfieldDidChanged(_ sender: UITextField) {

        if (postcodeTextField.text?.characters.count == 4) {
            self.postcode = postcodeTextField.text
            postcodeHas4Chars = true
        } else {
            postcodeHas4Chars = false
        }
    }

准备方法:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "CoffeeShopListWithPostcode" {
            if (postcodeHas4Chars == true) {
                if let list = segue.destination as? CoffeeShopListVC {
                    list.postcode = postcode
                } else {
                    print("Data NOT Passed!")
                }
            }
        } else { print("Id doesnt match with Storyboard segue Id")
        }
    }

代码有效,我可以将邮政编码发送到下一个 ViewController,但是如何更改代码以在第四次输入后自动调用该方法? 此时,用户必须手动退出输入才能执行。

最佳答案

每次文本字段的文本更改时,检查文本是否为 4 个字符。如果是,调用 performSegue(withIdentifier, sender:)。简单:

@IBAction func postcodeTextfieldDidChanged(_ sender: UITextField) {

    if (postcodeTextField.text?.characters.count == 4) {
        self.postcode = postcodeTextField.text
        postcodeHas4Chars = true
        performSegue(withIdentifier: "CoffeeShopListWithPostcode", sender: self)
    } else {
        postcodeHas4Chars = false
    }
}

此外,请记住您连接到 editingChanged 事件而不是 valueChanged 事件

关于ios - 在用户输入有四个字符后,如何在 Swift 3 中调用准备方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281326/

相关文章:

swift - 如何创建模态动画,其中向上滑动屏幕上半部分,向下滑动屏幕下半部分

ios - Swift - 使用闭包在 init 方法中设置属性

swift - 在 Swift 中初始化类属性

swift - 将 pcm 加载到 AVAudioPCMBuffer

objective-c - 如何自动链接框架或库

iOS SDK - 与 socket 建立连接的正确方法?

iOS 启动屏幕不显示

ios - IOS改名变量UILabel、IBOutlet报错

cocoa - Swift 的 GeneratorOf<T> 疯狂初始化

swift - 如何将日期字符串数组转换为日期对象数组,Swift