最大长度UITextField [英] Max length UITextField

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

问题描述

当我尝试如何设置可以使用swift输入到UITextField的最大字符数?,我看到如果我使用所有10个字符,我不能删除字符。

When I've tried How to you set the maximum number of characters that can be entered into a UITextField using swift?, I saw that if I use all 10 characters, I can't erase the character too.

我只能取消操作(删除所有字符在一起)。

The only thing I can do is to cancel the operation (delete all the characters together).

有人知道如何不阻止键盘(所以我不能添加其他字母/符号/数字,但我可以使用退格)?

Does anyone know how to not block the keyboard (so that I can't add other letters/symbols/numbers, but I can use the backspace)?

推荐答案

尝试以下实现 -textField:shouldChangeCharactersInRange:replacementString:,它是 UITextFieldDelegate protocol:

Try the following implementation of -textField: shouldChangeCharactersInRange: replacementString: that is part of the UITextFieldDelegate protocol:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return true }

    let newLength = text.characters.count + string.characters.count - range.length
    return newLength <= 10 // Bool
}

然而,根据您的需要, (更多详情,请参阅 Swift 2中的字符串):

According to your needs, however, you may prefer this implementation (see Strings in Swift 2 for more details):

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return true }

    let newLength = text.utf16.count + string.utf16.count - range.length
    return newLength <= 10 // Bool
}






用法:


Usage:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField! // Link this to a UITextField in your storyboard
    let limitLength = 10

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else { return true }
        let newLength = text.characters.count + string.characters.count - range.length
        return newLength <= limitLength
    }

}

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

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