当我加载一个UIView时,我如何在iPhone SDK上设置UITextField的最大字符数?
当前回答
为了使它与任何长度的字符串剪切和粘贴工作,我建议将函数更改为如下内容:
#define MAX_LENGTH 20
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSInteger insertDelta = string.length - range.length;
if (textField.text.length + insertDelta > MAX_LENGTH)
{
return NO; // the new string would be longer than MAX_LENGTH
}
else {
return YES;
}
}
其他回答
你不能直接这样做- UITextField没有maxLength属性,但你可以设置UITextField的委托,然后使用:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
美国小妞Xamarin:
YourTextField.ShouldChangeCharacters =
delegate(UITextField textField, NSRange range, string replacementString)
{
return (range.Location + replacementString.Length) <= 4; // MaxLength == 4
};
下面的代码类似于sickp的答案,但是正确地处理复制-粘贴操作。如果尝试粘贴超过限制的文本,下面的代码将截断文本以符合限制,而不是完全拒绝粘贴操作。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
static const NSUInteger limit = 70; // we limit to 70 characters
NSUInteger allowedLength = limit - [textField.text length] + range.length;
if (string.length > allowedLength) {
if (string.length > 1) {
// get at least the part of the new string that fits
NSString *limitedString = [string substringToIndex:allowedLength];
NSMutableString *newString = [textField.text mutableCopy];
[newString replaceCharactersInRange:range withString:limitedString];
textField.text = newString;
}
return NO;
} else {
return YES;
}
}
在Swift 5.2中工作:
class AngListVC: UIViewController, UITextFieldDelegate {
@IBOutlet weak var angTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
angTextField.delegate = self
angTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let userText = angTextField.text ?? ""
var newText = ""
if range.length > 0 {
let txt = NSString(string: userText)
if txt.length > 0 {
newText = txt.replacingCharacters(in: range, with: "")
}
} else {
newText = userText + ""
}
return newText.count <= 3
}
@objc func textFieldDidChange(_ textField: UITextField) {
print("textFieldDidChange")
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length >= 50) {
return NO;
}
return YES;
}
推荐文章
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- CFNetwork SSLHandshake iOS 9失败
- 请求失败:不可接受的内容类型:文本/html使用AFNetworking 2.0
- 缺少推荐的图标文件-该包不包含iPhone / iPod Touch的应用程序图标,像素为“120x120”,png格式
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- Xcode构建失败“架构x86_64未定义的符号”
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?