我会正确地回答这个问题。
var a = 0
var b = 20
我希望用户在TextField
中输入数字,然后我可以将该数字保存到变量A中。然后我想做if
语句
if a == b {
//code
}
我遇到的问题是从文本字段输入该数字。
答案 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)
}
}