限制 Swift 2 中多个 UITextField 的长度 [英] Limit length of multiple UITextFields in Swift 2

查看:26
本文介绍了限制 Swift 2 中多个 UITextField 的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限制 TextField 长度的解决方案,但函数 count 已经更新,还有 count() 函数,所以我不'不明白如何使用它:

a solution to limit the length of a TextField but the function count has been updated, also count() function, so I don't understand how to use this:

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

以及如何更新它以处理多个 TextField ,我想我必须说如果

And how to update this to work on multiple TextField , I think I have to say if

textField = thisTextField.text...

推荐答案

shouldChangeCharactersInRange 执行以下操作(引自 docs)

shouldChangeCharactersInRange does the following (Quoted from the docs)

询问代表是否应该更改指定的文本.

Asks the delegate if the specified text should be changed.

您添加到此方法的代码检查它是否超出您的限制(在您的示例中,它是 10)并返回 false,这意味着 textField 不应更改值.如果没有超过限制,则返回true,textField会改变值.

Your added code to this method checks if it exceeds your limit (In your example, it is 10) and returns false which means that the textField should not change values. If it did not exceed the limit, it will return true, and the textField will change values.

要为多个 textField 执行此操作,您需要为多个 textField 设置出口,然后在此方法中使用一个简单的 if 语句即可完成这项工作.

To do this for multiple textFields, you will need to have outlets to your multiple textFields, and then a simple if statement inside this method will do the job.

@IBOutlet weak var textfield1: UITextField!
@IBOutlet weak var textfield2: UITextField!

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let newLength = textField.text.characters.count + string.characters.count - range.length
    if textField == textField1 {
        return newLength <= 10 // Bool
    } else if textField == textField2 {
        return newLength <= 15 // Bool
    }

    return true
}

为了能够在您的代码中使用上述方法,您的包含这些 textFields 的 UIViewController 将需要实现 UITextFieldDelegate 协议,然后通过设置 UITextField 的委托属性是 UIViewController.

To be able to use the above method in your code, your UIViewController which contains these textFields will need to implement the UITextFieldDelegate protocol, and then by setting the UITextField's delegate property to be that UIViewController.

还有关于 count 方法.它已经更新了很多次.计算字符串的字符数:

Also regarding the count method. It has been updated many times. To count the number of characters for a string:

Swift1.2 之前 -> countElements(string)
Swift1.2 -> count(string)
Swift2 -> string.characters.count

Before Swift1.2 -> countElements(string)
Swift1.2 -> count(string)
Swift2 -> string.characters.count

这篇关于限制 Swift 2 中多个 UITextField 的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆