当我加载一个UIView时,我如何在iPhone SDK上设置UITextField的最大字符数?
当前回答
我创建了这个UITextFieldLimit子类:
支持多个文本框 设置文本长度限制 粘贴的预防 在文本域中显示左字符的标签,当您停止编辑时隐藏。 当没有字符时摇动动画。
获取UITextFieldLimit.h和UITextFieldLimit。m从这个GitHub存储库:
https://github.com/JonathanGurebo/UITextFieldLimit
开始测试吧!
标记你的故事板创建的UITextField,并使用身份检查器链接到我的子类:
然后可以将其链接到IBOutlet并设置限制(默认为10)。
你的ViewController.h文件应该包含:(如果你不想修改设置,比如限制)
#import "UITextFieldLimit.h"
/.../
@property (weak, nonatomic) IBOutlet UITextFieldLimit *textFieldLimit; // <--Your IBOutlet
ViewController。m文件应该@synthesize textFieldLimit。
在ViewController中设置文本长度限制。m文件:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[textFieldLimit setLimit:25];// <-- and you won't be able to put more than 25 characters in the TextField.
}
希望这门课能帮到你。好运!
其他回答
其他答案不处理用户可以从剪贴板粘贴长字符串的情况。如果我粘贴一个很长的字符串,它应该被截断,但显示出来。 在你的委托中使用这个:
static const NSUInteger maxNoOfCharacters = 5;
-(IBAction)textdidChange:(UITextField * )textField
{
NSString * text = textField.text;
if(text.length > maxNoOfCharacters)
{
text = [text substringWithRange:NSMakeRange(0, maxNoOfCharacters)];
textField.text = text;
}
// use 'text'
}
斯威夫特4
import UIKit
private var kAssociationKeyMaxLength: Int = 0
extension UITextField {
@IBInspectable var maxLength: Int {
get {
if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
return length
} else {
return Int.max
}
}
set {
objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
}
}
@objc func checkMaxLength(textField: UITextField) {
guard let prospectiveText = self.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
let substring = prospectiveText[..<indexEndOfText]
text = String(substring)
selectedTextRange = selection
}
}
编辑:内存泄漏问题修复。
这个简单的方法怎么样?它对我来说很好。
extension UITextField {
func charactersLimit(to:Int) {
if (self.text!.count > to) {
self.deleteBackward()
}
}
}
然后:
someTextField.charactersLimit(to:16)
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 } }
稍微超出了回答原来的问题,并扩展了Frouo的答案,这里有扩展来修剪空白字符串和最大长度,并利用这些字符串扩展来修剪UITextField到最大长度:
// In String_Extensions.swift
extension String {
func trimmedString() -> String {
var trimmedString = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let components = trimmedString.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter { count($0) > 0 }
return " ".join(components)
}
func trimmedStringToMaxLength(maxLength: Int) -> String {
return trimmedString().substringToIndex(advance(startIndex, min(count(self), maxLength))).trimmedString()
}
}
// In UITextField_Extensions.swift
private var maxLengthDictionary = [UITextField : Int]()
private var textFieldMaxLength = 20
extension UITextField {
@IBInspectable var maxLength: Int {
get {
if let maxLength = maxLengthDictionary[self] {
return maxLength
} else {
return textFieldMaxLength
}
}
set {
maxLengthDictionary[self] = newValue < textFieldMaxLength + 1 ? newValue : textFieldMaxLength
}
}
func trimAndLimitToMaxLength() {
text = text.trimmedStringToMaxLength(maxLength)
}
}
let someTextField = UITextField()
let someString = " This is a string that is longer than allowable for a text field. "
someTextField.text = someString
someTextField.trimAndLimitToMaxLength()
println(someTextField.text) // Prints "This is a string tha"
let anotherTextField = UITextField()
anotherTextField.maxLength = 5
anotherTextField.text = someString
anotherTextField.trimAndLimitToMaxLength()
println(anotherTextField.text) // Prints "This"
trimAndLimitToMaxLength() could be used in UITextFieldDelegate's textFieldDidEndEditing(_:) so that a user could enter or paste in a longer than acceptable string and then shorten it vs. just cutting off the input at the max length. In doing this, I would also set attributed text styles to indicate any portion of the text that goes beyond the acceptable length (e.g., [NSBackgroundColorAttributeName : UIColor.redColor(), NSForegroundColorAttributeName : UIColor.whiteColor(), NSStrikethroughStyleAttributeName : NSNumber(int: 1)]
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务