【问题标题】:how to get number in stackview textfield form dynamic numeric pad for otp in swift如何在stackview文本字段中快速获取otp的动态数字键盘中的数字
【发布时间】:2018-08-09 05:59:13
【问题描述】:

如何在 stackview 文本字段表单中获取数字,用于 swift 中的 otp 动态数字键盘 如何在stackview文本字段中快速获取otp的动态数字键盘中的数字 如何在stackview文本字段中快速获取otp的动态数字键盘中的数字

@IBAction func one(_ sender: Any) {

    operation = (sender as AnyObject).tag

    if (sender as AnyObject).tag == 1 {
         textField1.text  = "0";

    }
    if (sender as AnyObject).tag == 2 {

        text1.text = "1";

    }
    if (sender as AnyObject).tag == 3 {

        text1.text = "2";

    }
    if (sender as AnyObject).tag == 4 {

        text1.text = "3";

    }
    if (sender as AnyObject).tag == 5 {

        text1.text = "4";

    }
    if (sender as AnyObject).tag == 6{

        text1.text = "5";

    }
    if (sender as AnyObject).tag == 7 {

        text1.text = "6";

    }
    if (sender as AnyObject).tag == 8 {

        text1.text = "7";

    }
    if (sender as AnyObject).tag == 9 {

        text1.text  = "8";

    }
    if (sender as AnyObject).tag == 10 {

        text1.text  = "9";
    }
}

【问题讨论】:

    标签: swift uitextfield uistackview


    【解决方案1】:

    在您的按钮操作中,如果您将发件人类型设置为 UIButton,则所有 if 条件都是不必要的,因此您可以直接访问 UIButtoncurrentTitle 属性。另外,不要尝试从 stackView 获取 textField,您可以制作 IBOutletCollectionUITextField,如果您不知道如何男性化 IBOutletCollection,您可以关注此 medium documentation。创建一个字符串变量来存储OTP,并用它来为textField赋值

    @IBOutlet var otpFields: [UITextField]! //Make sure you add textFields in proper order
    var otpString = "" // to assign value to textField.
    

    现在添加一种方法来将文本从 otpString 设置为 textFields,并更改您的按钮操作,如下所示。

    func setupOTPFields() {
        for (index,ch) in otpString.enumerated() {
            otpFields[index].text = String(ch)
        }
    }
    
    //action of 0-9 button
    @IBAction func one(_ sender: UIButton) {
        if otpString.count <= 6 { //Because you only have 6 character otp
            otpString += (sender.currentTitle ?? "")
            //Call setup field method
            self.setupOTPFields()
        }
    }
    
    //action of c button
    @IBAction func cButtonClick(_ sender: UIButton) {
        if !otpString.isEmpty {
            otpString = String(otpString.dropLast())
            //Call setup field method
            self.setupOTPFields()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-29
      • 2012-11-29
      • 2014-10-30
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 2019-09-18
      相关资源
      最近更新 更多