如何使用 swift 设置可以输入 UITextField 的最大字符数? [英] How to you set the maximum number of characters that can be entered into a UITextField using swift?

查看:911
本文介绍了如何使用 swift 设置可以输入 UITextField 的最大字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制UITextField中的字符数为10,如果用户输入超过10,只记录前 10 个字符?

How do you limit the number of characters in a UITextField to 10, and if the user enters more than 10, only record the first 10 characters?

推荐答案

该解决方案也处理用户粘贴文本或点击删除键的问题.

This solution deals with a user pasting text or tapping delete key too.

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

    let length = count(textField.text.utf16) + count(string.utf16) - range.length

    return length <= 10 

}

这篇关于如何使用 swift 设置可以输入 UITextField 的最大字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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