【问题标题】:How to limit the numbers in the text field in Swift?如何限制 Swift 中文本字段中的数字?
【发布时间】:2015-04-10 16:31:51
【问题描述】:

我希望用户在文本字段中填写一个从 0 到 60 的数字。 如何将数字字符限制为 2? 如何将最大数量限制为 60? 以及如何取消文本字段上的“粘贴”选项,使用户无法粘贴字母?

【问题讨论】:

标签: ios iphone ipad swift


【解决方案1】:

我认为有两种方法可以做到这一点。

实现UITextFieldDelegate并实现函数

func textField(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool {

    var startString = ""

    if textField.text != nil {
        startString += textField.text!
    }

    startString += string

    var limitNumber = startString.toInt()

    if limitNumber > 60 {
        return false
    } else {
        return true
    }
}

在此每次检查到目前为止已输入到UITextField 的内容,转换为Integer,如果新值高于60,则返回false。 (同时向用户显示相应的错误)。

我认为更好的方法是提供UIPickerView

【讨论】:

  • 我更喜欢文本字段的代码,但您能继续编写代码吗?在你的代码之后我没有得到我需要做的事情。
  • 这就是答案!伟大的!如果我有 2 个文本字段,你知道我需要做什么吗?
  • 假设您有 2 个 textField,ageTextField 和 heightTextField。函数中接收到的第一个参数是 textField 在上面你把检查 if (textField == ageTextField) 并执行你的代码。
【解决方案2】:

使用文本字段的委托方法

其中 10 是文本字段的最大限制...

      func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let newLength = countElements(textField.text) + countElements(string) - range.length
       return newLength <= 10 // Bool
 }

如果 countElements 在最新版本的 s 中不起作用 wift 使用 count 而不是 countElements。

【讨论】:

    【解决方案3】:

    禁用复制和粘贴:

    func canPerformAction(_ action: Selector, withSender sender: AnyObject?) -> Bool
    {
        if action == "paste:"
            {return false}
        return super.canPerformAction(action,withSender:sender)
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多