एक iOS डेवलपर के रूप में टेक्स्ट फील्ड और इसके ऑपरेशन्स के साथ मैनिपुलेट करना आना चाहिए, Apple ने पहले से ही UITextFieldDelegate प्रोटोकॉल प्रदान किया है।
इसके बारे में यहाँ और पढ़ें: https://developer.apple.com/documentation/uikit/uitextfielddelegate
आपने कई एप्लिकेशन देखे होंगे जहां फॉर्म्स शामिल होते हैं, और आप टाइप करते समय कैरेक्टर्स की संख्या देखते हैं विशेष रूप से उन फॉर्म्स पर जहां कैरेक्टर्स एक निश्चित संख्या तक सीमित होते हैं।
इस पोस्ट में हम वही देखेंगे कि टेक्स्ट फील्ड में टाइप करते समय कैरेक्टर काउंट कैसे प्रदर्शित करें।
चरण 1: प्रोजेक्ट बनाएं
Xcode खोलें → New Project → Single View Application → नाम दें "TextFieldCount"
चरण 2: UI सेटअप
Main.storyboard खोलें और नीचे दिखाए अनुसार टेक्स्ट फील्ड और लेबल जोड़ें, लेबल और टेक्स्ट फील्ड के लिए @IBOutlet बनाएं और नाम दें lblCount, txtInputBox।

चरण 3: UITextFieldDelegate कंफर्म करें
class ViewController: UIViewController, UITextFieldDelegate {
txtInputBox.delegate = self
}
चरण 4: shouldChangeCharactersIn डेलीगेट इम्प्लीमेंट करें
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(textField == txtInputBox){
let strLength = textField.text?.count ?? 0
let lngthToAdd = string.count
let lengthCount = strLength + lngthToAdd
self.lblCount.text = "\(lengthCount)"
}
return true
}
चरण 5: एप्लिकेशन चलाएं
उदाहरण
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var txtInputBox: UITextField!
@IBOutlet var lblCount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
txtInputBox.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(textField == txtInputBox){
let strLength = textField.text?.count ?? 0
let lngthToAdd = string.count
let lengthCount = strLength + lngthToAdd
self.lblCount.text = "\(lengthCount)"
}
return true
}
}
आउटपुट
