如何从TextField获取数字输入?

时间:2018-04-04 04:11:05

标签: swift

我会正确地回答这个问题。

var a = 0 
var b = 20

我希望用户在TextField中输入数字,然后我可以将该数字保存到变量A中。然后我想做if语句

if a == b {
    //code
}

我遇到的问题是从文本字段输入该数字。

2 个答案:

答案 0 :(得分:0)

您可以在文本字段中检查输入以获取数字

<强> Swift4

let text = textField.text ?? ""
guard let number = Int(text) else {
    print("Must be input the number")
    return
}
// Do your task with number
a = number

答案 1 :(得分:0)

尝试此类函数

class SourceVC: UIViewController
{
    @IBOutlet weak var sampleTF: UITextField!{
        didSet{
            sampleTF.delegate = self
        }
    }
    /// TF value
    var a : Int = 0
    var b : Int = 20

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    /// Assuming this button action to get Value from TF
    @IBAction func naviagteToDestination(_ sender: Any)
    {
        a = Int((sampleTF.text?.trimmingCharacters(in: .whitespaces))!)!

        if a == b {
            print("Execute")
        }
        else{
            print("Dont Execute")
        }
    }
}

extension SourceVC : UITextFieldDelegate
{
    /// This will Limit TF to accept only Numbers
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        let allowedCharacters = CharacterSet.decimalDigits
        let characterSet = CharacterSet(charactersIn: string)
        return allowedCharacters.isSuperset(of: characterSet)
    }
}