首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在swift中输入所有UITextFields中的文本之前,如何禁用按钮?

在swift中输入所有UITextFields中的文本之前,如何禁用按钮?
EN

Stack Overflow用户
提问于 2015-04-04 23:33:15
回答 3查看 4.5K关注 0票数 1

我需要一种方法来禁用保存按钮,直到所有必需的文本框中都输入了文本?我正在开发Swift中的应用程序,我已经在Objective-c中找到了很多答案。因为我现在完全掌握了Objective-c的知识,所以我无法弄清楚它的意思。

有没有人有可以在Swift中完成的解决方案?

我知道如何启用/禁用按钮。我还知道如何检查文本字段是否为空。我只是不确定如何创建它,以便我的代码总是检查它是否为空。我尝试了一次while循环,但正如我所料,这会冻结一切。

EN

回答 3

Stack Overflow用户

发布于 2015-07-28 10:10:09

列出实现这一目标的方法之一:

代码语言:javascript
运行
复制
class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var button: UIButton!

    //Need to have the ViewController extend UITextFieldDelegate for using this feature
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        // Find out what the text field will be after adding the current edit
        let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

        if !text.isEmpty{//Checking if the input field is not empty
            button.userInteractionEnabled = true //Enabling the button
        } else {
            button.userInteractionEnabled = false //Disabling the button
        }

        // Return true so the text field will be changed
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //Setting the Delegate for the TextField
        textField.delegate = self
        //Default checking and disabling of the Button
        if textField.text.isEmpty{
            button.userInteractionEnabled = false // Disabling the button
        }
    }
}

Reference Link for the above solution

票数 3
EN

Stack Overflow用户

发布于 2015-04-05 00:01:01

尽管到目前为止给出了所有的评论,为了不进一步破坏评论区,我试着给出一些关于如何解决你的问题的提示:

  • 将所有文本字段放在outlet集合中,并将所有文本字段的委托设置为您的viewController
  • implement委托委托的didEndEditing方法,并在该方法中迭代outlet集合以检查每个文本字段的输入

请注意,这只是实现这一点的一种方法,但您可能会明白这一点。

票数 2
EN

Stack Overflow用户

发布于 2015-04-04 23:54:30

使用文本字段的委托方法(或目标操作模式)检查用户继续操作所需的条件。如果满足这些条件,请启用该按钮。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29448185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档