将文本字段限制为 SWIFT 4 中的正整数

Restrict text field only to positive integers in SWIFT 4

我有一个文本字段,它使用包含整数的按钮来增加金额,我不想要负数,它将从零开始。我怎样才能做到这一点?

 @IBAction func beyazDOWN(_ sender: UIButton) {

    calculateBUTTON.setTitle("=", for: .normal)

    UIButton.animate(withDuration: 0.05, animations: {
        sender.transform = CGAffineTransform(scaleX: 0.700, y: 0.700)
    }, completion: { finish in
        UIButton.animate(withDuration: 0.1, animations:
            { sender.transform = CGAffineTransform.identity })
    })

    num3 = Int(field3.text!)!;
    self.field3.text = String(num3 - 1);


}
var amount:Int{
    willSet{
      if newValue < 0{
        textfield.text = "0"
      }
    }
}

其中 amount 是您将在文本字段上显示的值 喜欢 textfield.text = amount

按照你的代码:

var num3:Int{
    willSet{
      if newValue < 1{
        beyazDOWN.isEnabled = false
      }
      else{
        beyazDOWN.isEnabled = true 
      } 
    }
}

或者,您可以执行以下操作:

@IBAction func beyazDOWN(_ sender: UIButton) {

    num3 = Int(field3.text!)!; 
    if num3 <= 1{
      return
    }


    calculateBUTTON.setTitle("=", for: .normal)

    UIButton.animate(withDuration: 0.05, animations: {
        sender.transform = CGAffineTransform(scaleX: 0.700, y: 0.700)
    }, completion: { finish in
        UIButton.animate(withDuration: 0.1, animations:
            { sender.transform = CGAffineTransform.identity })
    })

    self.field3.text = String(num3 - 1);

}