【问题标题】:Set the maximum amount limit on a UITextField in Swift在 Swift 中设置 UITextField 的最大数量限制
【发布时间】:2021-10-31 16:46:28
【问题描述】:

我知道如何在 UITextField 上设置字符长度限制。但我正在寻找一个想法,如何在 UITextField 上设置数量限制,使其不能超过该限制。

我想限制 TextField 可以接受 0 到 1000000 之间的值

我尝试使用 UITextFieldDelegate 的 方法获得它

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if let amount = Int(textField.text!) ,amount>1000000{
            return false
        }else{
            return true
        }
    }

但我无法达到结果。

【问题讨论】:

  • 也许你在看这个``` let amount = Int((textField.text ?? "") + string) ?? 0 if (0
  • 这段代码应该可以工作,确保这个方法被调用。如果不是,请确保为文本字段 delegate 设置正确的对象
  • 1000000 也是一个巨大的数字,我会先测试 10 之类的东西以确保它一开始就可以工作
  • @RajaKishan 是的,它起作用了......我错过了添加传入字符串谢谢
  • 我认为您的要求是只允许用户输入 0 到 1000000 之间的金额,对吧?

标签: ios swift swift3


【解决方案1】:

您还需要使用文本字段值添加当前字符串。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if let text = textField.text,
           let amount = Int((text + string).trimmingCharacters(in: .whitespaces)),
           (0 < amount), (amount < 1000000) {
            return true
        }
        return false
    }

【讨论】:

    猜你喜欢
    • 2014-12-22
    • 2018-03-12
    • 2015-09-30
    • 1970-01-01
    • 2023-04-02
    • 2011-02-01
    • 2018-05-30
    • 2016-01-01
    相关资源
    最近更新 更多