Setting maximum number of characters of `UITextView ` and `UITextField `
Update Swift 4.X
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let numberOfChars = newText.count
return numberOfChars < 10 // 10 Limit Value
}
Try this out:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
let numberOfChars = newText.characters.count // for Swift use count(newText)
return numberOfChars < 10;
}
Set the maximum character length of a UITextField in Swift
Your view controller should conform to
UITextFieldDelegate
, like below:class MyViewController: UIViewController, UITextFieldDelegate {
}Set the delegate of your textfield:
myTextField.delegate = self
Implement the method in your view controller:
textField(_:shouldChangeCharactersInRange:replacementString:)
All together:
class MyViewController: UIViewController, UITextFieldDelegate // Set delegate to class
@IBOutlet var mytextField: UITextField // textfield variable
override func viewDidLoad() {
super.viewDidLoad()
mytextField.delegate = self // set delegate
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool
{
let maxLength = 4
let currentString: NSString = textField.text
let newString: NSString = currentString.stringByReplacingCharactersInRange(range, withString: string)
return newString.length <= maxLength
}
For Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 1
let currentString: NSString = (textField.text ?? "") as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= maxLength
}
For Swift 5
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 1
let currentString = (textField.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
return newString.count <= maxLength
}
Allowing only a specified set of characters to be entered into a given text field
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var result = true
if mytextField == textField {
if count(string) > 0 {
let disallowedCharacterSet = NSCharacterSet(charactersInString: "0123456789.-").invertedSet
let replacementStringIsLegal = string.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
result = replacementStringIsLegal
}
}
return result
}
How to program an iOS text field that takes only numeric input with a maximum length
Swift - Limit the number of characters in lines for UITextview
Implement shouldChangeTextIn and return false if any line has more than the allowed number of characters:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let maxAllowedCharactersPerLine = 10
let lines = (textView.text as NSString).replacingCharacters(in: range, with: text).components(separatedBy: .newlines)
for line in lines {
if line.characters.count > maxAllowedCharactersPerLine {
return false
}
}
return true
}
Set the maximum character length of a UITextField
While the UITextField
class has no max length property, it's relatively simple to get this functionality by setting the text field's delegate
and implementing the following delegate method:
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;
}
Swift
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
}
Before the text field changes, the UITextField asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it's current length and the string length we're inserting (either through pasting copied text or typing a single character using the keyboard), minus the range length. If this value is too long (more than 25 characters in this example), return NO
to prohibit the change.
When typing in a single character at the end of a text field, the range.location
will be the current field's length, and range.length
will be 0 because we're not replacing/deleting anything. Inserting into the middle of a text field just means a different range.location
, and pasting multiple characters just means string
has more than one character in it.
Deleting single characters or cutting multiple characters is specified by a range
with a non-zero length, and an empty string. Replacement is just a range deletion with a non-empty string.
A note on the crashing "undo" bug
As is mentioned in the comments, there is a bug with UITextField
that can lead to a crash.
If you paste in to the field, but the paste is prevented by your validation implementation, the paste operation is still recorded in the application's undo buffer. If you then fire an undo (by shaking the device and confirming an Undo), the UITextField
will attempt to replace the string it thinks it pasted in to itself with an empty string. This will crash because it never actually pasted the string in to itself. It will try to replace a part of the string that doesn't exist.
Fortunately you can protect the UITextField
from killing itself like this. You just need to ensure that the range it proposes to replace does exist within its current string. This is what the initial sanity check above does.
swift 3.0 with copy and paste working fine.
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
}
Hope it's helpful to you.
Limit number of characters in uitextview
You should be looking for an empty string instead, as the apple reference says
If the user presses the Delete key, the length of the range is 1 and an empty string object replaces that single character.
I think the check you actually want to make is something like [[textView text] length] - range.length + text.length > 140
, to account for cut/paste operations.
Limit the number of Characters for an IBOutlet TextView, Swift
Please have a look of below question
Set the maximum character length of a UITextField (In my answer you can also see for UITextView)
Instead of writing duplicate code everywhere, You can create an extension of UITextView
or UITextField
to set the max length
Update:
Comment Explanation:
First thing, You need to remove the UITextView
delegate method from your current view controller. Because extension of UITextView
is internally used UITextViewDelegate
Note: Delegate is one to one communication. In your case, if you implement delegate in the current view controller then an extension of UITextView
is not worked.
How to limit characters in UITextView iOS
1) add UITextViewDelegate in your viewcontroller like this
@interface ViewController : UIViewController <UITextViewDelegate>
Each time a user types a character on the keyboard, just before the character is displayed,following method get called. This is a handy location to test the characters that a user is typing and disallow specific characters you want to restrict.
textView:shouldChangeCharactersInRange:replacementString
2) then write following code.
instead of 140 you can put whatever number you want.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
return textView.text.length + (text.length - range.length) <= 140;
}
For more help take a look at UItextView
Swift 2.0 solution
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
return textView.text.characters.count + (text.characters.count - range.length) <= textViewLimit
}
Limit the number of lines for UITextview
You have the right idea, but the wrong method. textView:shouldChangeTextInRange:replacementText:
is called whenever the text is going to change; you can access the current content of the text view using its text
property, and you can construct the new content from the passed range and replacement text with [textView.text stringByReplacingCharactersInRange:range withString:replacementText]
. You can then count the number of lines and return YES to allow the change or NO to reject it.
Related Topics
How to Change Uibutton Title Color
How to Move Cursor from One Text Field to Another Automatically in Swift iOS Programmatically
How to Detect Call Incoming Programmatically
Error: Uiview's Window Is Not Equal to Another View's Window
Run a Swift 2.0 App Forever in Background to Update Location to Server
Firebase: Cannot Upload Production Apns Certificate
Nslocalizedstring Only Retrieves the Key, Not the Value in Localizable.Strings (Ios)
Crashlytics iOS - Log Caught Exception
Setting Maximum Number of Characters of 'Uitextview ' and 'Uitextfield '
Perform Push Segue After an Unwind Segue
Loading a Resource (E.G. Storyboard) in a Swift Framework
iOS Changing Uiscrollview Scrollbar Color to Different Colors
What Do JSONserialization Options Do and How Do They Change JSONresult
How to Stop Uitableview from Clipping Uitableviewcell Contents in iOS 7
Is There Function to Convert Uicolor to Hue Saturation Brightness
Mapkit iOS 9 Detailcalloutaccessoryview Usage
"Could Not Find Any Information for Class Named Viewcontroller"
Create and Store PDF Document Programmatically Using Swift for iOS