How to do a live UITextField count while typing (Swift)?
To use the function below you need to implement the UITextFieldDelegate protocol
on the text field you want to count. This gets called every time the UITextField
s text changes:
Your class declaration should look something like this
class ViewController: UIViewController, UITextFieldDelegate
You should have an @IBOutlet
similar to this
@IBOutlet var txtValue: UITextField
Set the UITextField
s delegate to self
.
override func viewDidLoad() {
super.viewDidLoad()
txtValue.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
mylabel.text = String(newLength) // Set value of the label
// myCounter = newLength // Optional: Save this value
// return newLength <= 25 // Optional: Set limits on input.
return true
}
Note that this function is called on all UITextField
s so if you have several UITextField
s you will need to add a logic to know witch one is calling this function.
put character count and character type limit for the textfield swift 4
You can't just make up delegate method names. You need to implement the proper method and do all of your needed checking in the one method.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if newString.count > 6 {
return false
}
return newString.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
Swift 3: Show characters remaining in UITextField
You need the UITextFieldDelegate
.
Set the delegate in viewDidLoad
to the textField
Outlet.
And then you use the shouldChangeCharactersInRange
function.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
// here you set the start value 55 of your label
label.text = String(55)
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let length = text.characters.count + string.characters.count - range.length
// create an Integer of 55 - the length of your TextField.text to count down
let count = 55 - length
// set the .text property of your UILabel to the live created String
label.text = String(count)
// if you want to limit to 55 charakters
// you need to return true and <= 55
return length <= 55 // To just allow up to 55 characters
}
}
Dismiss keyboard after a user entered 11 digit
This is how it works
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// YOU SHOULD FIRST CHECK FOR THE BACKSPACE. IF BACKSPACE IS PRESSED ALLOW IT
if string == "" {
return true
}
if let characterCount = textField.text?.count {
// CHECK FOR CHARACTER COUNT IN TEXT FIELD
if characterCount >= 11 {
// RESIGN FIRST RERSPONDER TO HIDE KEYBOARD
return textField.resignFirstResponder()
}
}
return true
}
EDIT
1) You should set the IBOutlet to your textField
2) Set delegate to self, on your textField.
3) YourViewController: UIViewController, UITextFieldDelegate { }
4) Implement the delegate method as in above. check for the backspace and allow if user enters backspace to remove characters from textField.
iPhone how to get UITextField's text while typing?
- First add one
UITextField
andUILabel
to storyboard / nib - Now assign
IBOutlet
forUILabel
(Here I have used myLabel) - Assign
UITextFieldDelegate
to file owner, also implement the same delegate in .h file Use these lines of code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self updateTextLabelsWithText: newString];
return YES;
}
-(void)updateTextLabelsWithText:(NSString *)string
{
[myLabel setText:string];
}
Hope this helps.
UITextField - Limit text lenght not by character count
What you want to do is instead of calculating the maximum number of characters of the new string, calculate it's width in points and compare it to the width you need.
[Swift]
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let combinedString = textField.attributedText!.mutableCopy() as NSMutableAttributedString
combinedString.replaceCharactersInRange(range, withString: string)
return combinedString.size().width > textField.bounds.size.width
}
You might need to edit the attributes to get it to render on a single line.
SwiftUI display characters count remaining in a label/text
I needed something similar so I got this extension for the Binding class
extension Binding {
func didSet(execute: @escaping (Value) ->Void) -> Binding {
return Binding(
get: {
return self.wrappedValue
},
set: {
let snapshot = self.wrappedValue
self.wrappedValue = $0
execute(snapshot)
}
)
}
}
This will allow to listen to changes on bindings
Now comes the easy part, getting the count and showing it
@State var charCount: Int
// code until this section
Section(header: Text("Additional Information")) {
MultilineTextView(text: $notes.didSet(execute: { (value: String) in self.countLeft(value) }))
Text("\(String(charCount))")
}
// outside the body
func getCount(_ value: String) {
self.charCount = value.count
}
You can improve your UI using ZStack
, VStack
, HStack
and Spacer()
I can not figure out how do you want to display it so I just took your example.
Also, if it's a simple function, for example a count, you don't need to declare a function you can write it in the closure like so
// ...
MultilineTextView(text: $notes.didSet(execute: { (value: String) in self.charCount = value.count }))
How to implement a simple 'live' word count in a UITextView
I used to create like this, for prevent UITextview to type only 140 characters.
And i shown that count in UILabel like this
-(void)textViewDidChange:(UITextView *)textView
{
int len = textView.text.length;
lbl_count.text=[NSString stringWithFormat:@"%i",140-len];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if([text length] == 0)
{
if([textView.text length] != 0)
{
return YES;
}
}
else if([[textView text] length] > 139)
{
return NO;
}
return YES;
}
this may help for you!!!
Related Topics
Changing the Status Bar Text Color in Splash Screen iOS 7
Is It Necessary to Use [Unowned Self] in Closures of Uiview.Animatewithduration(...)
React Native iOS Build:Can't Find Node
How to Change Color of Uitableviewcell When Selecting
How to Create a Glow Around a Sprite via Skeffectnode
Ios: Delete All Core Data Swift
How Does Google's Custom iOS Keyboard, Gboard, Programmatically Dismiss the Frontmost App
Nsattributedstring Inserting a Bullet Point
How to Create an Ibinspectable of Type Enum
"Initialize" Class Method for Classes in Swift
How to List All Classes Conforming to Protocol in Swift
iOS Unable to Find Plugins, Android Fine
How to Tell If Your Code Is Running on an iPhone or an Iphone3G
Get Udid of iOS Device Programmatically