当我加载一个UIView时,我如何在iPhone SDK上设置UITextField的最大字符数?
当前回答
最好的方法是设置文本更改通知。在视图控制器方法的-awakeFromNib中,你需要:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitTextField:) name:@"UITextFieldTextDidChangeNotification" object:myTextField];
然后在同一个类中添加:
- (void)limitTextField:(NSNotification *)note {
int limit = 20;
if ([[myTextField stringValue] length] > limit) {
[myTextField setStringValue:[[myTextField stringValue] substringToIndex:limit]];
}
}
然后链接出口myTextField到你的UITextField,它将不让你添加任何字符后,你达到限制。一定要把这个添加到你的dealloc方法中:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:myTextField];
其他回答
适用于Swift 3.1或更高版本
首先添加协议UITextFieldDelegate
如:-
class PinCodeViewController: UIViewController, UITextFieldDelegate {
.....
.....
.....
}
之后创建你的UITextField并设置委托
完成经验:-
import UIKit
class PinCodeViewController: UIViewController, UITextFieldDelegate {
let pinCodetextField: UITextField = {
let tf = UITextField()
tf.placeholder = "please enter your pincode"
tf.font = UIFont.systemFont(ofSize: 15)
tf.borderStyle = UITextBorderStyle.roundedRect
tf.autocorrectionType = UITextAutocorrectionType.no
tf.keyboardType = UIKeyboardType.numberPad
tf.clearButtonMode = UITextFieldViewMode.whileEditing;
tf.contentVerticalAlignment = UIControlContentVerticalAlignment.center
return tf
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(pinCodetextField)
//----- setup your textfield anchor or position where you want to show it-----
// after that
pinCodetextField.delegate = self // setting the delegate
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !(textField.text?.characters.count == 6 && string != "")
} // this is return the maximum characters in textfield
}
这限制了字符的数量,但也确保您可以粘贴字段,直到最大限制。
- (void)textViewDidChange:(UITextView *)textView
{
NSString* str = [textView text];
str = [str substringToIndex:MIN(1000,[str length])];
[textView setText:str];
if([str length]==1000) {
// show some label that you've reached the limit of 1000 characters
}
}
你也可以在Swift 4中使用NotificationCenter来做到这一点
NotificationCenter.default.addObserver(self, selector: #selector(self.handleTextChange(recognizer:)), name: NSNotification.Name.UITextFieldTextDidChange, object: yourTextField)
@objc func handleTextChange(recognizer: NSNotification) {
//max length is 50 charater max
let textField = recognizer.object as! UITextField
if((textField.text?.count)! > 50) {
let newString: String? = (textField.text as NSString?)?.substring(to: 50)
textField.text = newString
}
}
虽然UITextField类没有max length属性,但是通过设置文本字段的委托并实现以下委托方法来获得这个功能相对简单:
objective - c
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Prevent crashing undo bug – see note below.
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 25;
}
斯威夫特
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentCharacterCount = textField.text?.count ?? 0
if range.length + range.location > currentCharacterCount {
return false
}
let newLength = currentCharacterCount + string.count - range.length
return newLength <= 25
}
在文本字段更改之前,UITextField会询问委托是否应该更改指定的文本。此时文本字段还没有改变,所以我们获取它的当前长度和我们插入的字符串长度(通过粘贴复制的文本或使用键盘输入单个字符),减去范围长度。如果该值太长(本例中超过25个字符),则返回NO以禁止更改。
当在文本字段的末尾输入单个字符时,范围。Location是当前字段的长度和范围。Length将为0,因为我们没有替换或删除任何东西。插入到文本字段的中间只是意味着一个不同的范围。位置,粘贴多个字符意味着字符串中有多个字符。
删除单个字符或删除多个字符由一个长度非零的范围和一个空字符串指定。替换只是一个非空字符串的范围删除。
关于崩溃的“撤消”错误的说明
正如评论中提到的,UITextField有一个bug,可能导致崩溃。
如果粘贴到字段,但验证实现阻止了粘贴,则粘贴操作仍会记录在应用程序的撤销缓冲区中。如果你随后触发一个撤销(通过摇动设备并确认撤销),UITextField将尝试用一个空字符串替换它认为它粘贴到自己的字符串。这将会崩溃,因为它从未将字符串粘贴到自身。它将尝试替换字符串中不存在的部分。
幸运的是,你可以保护UITextField不像这样杀死自己。您只需要确保它建议替换的范围确实存在于其当前字符串中。这就是上面最初的健全性检查所做的工作。
Swift 3.0与复制和粘贴工作良好。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let str = (textView.text + text)
if str.characters.count <= 10 {
return true
}
textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 10))
return false
}
希望对你有帮助。
Swift 4 + 2。
通过实现UITextFieldDelegate方法
ViewController: class MyViewController: UIViewController { let MAX_LENGTH = 256 @IBOutlet weak var myTextField: UITextField! override viewDidLoad() { self.myTextField.delegate = self } } Delegate: extension MyViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let userText = textView.text ?? "" var newText = "" if range.length > 0 { let txt = NSString(string: userText) if txt.length > 0 { newText = txt.replacingCharacters(in: range, with: text) } } else { newText = userText + text } return newText.count <= MAX_LENGTH } }
推荐文章
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 在iPhone上确定用户是否启用了推送通知
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- 错误ITMS-9000:“冗余二进制文件上传。火车1.0版本已经有一个二进制版本上传。
- Swift -转换为绝对值
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容
- 在代码中为UIButton设置一个图像
- NSRange从Swift Range?
- UICollectionView中的单元格间距