例如,如果用户输入字符串“1234567890”,则格式化版本将为“1234 5678 90”。这种格式可以更轻松地以更易于理解的格式显示某些类型的数据,例如信用卡号码或电话号码。
首先,确保你的视图控制器符合 UITextFieldDelegate 协议:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
// Your other code
override func viewDidLoad() {
super.viewDidLoad()
// Assuming you have a UITextField named textField
textField.delegate = self
}
// Your other code
}
然后,实现 textField(_:shouldChangeCharactersIn:replacementString:) 方法,每 4 个字符添加空格: 迅速
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Remove any spaces from the current text
let textWithoutSpaces = textField.text?.replacingOccurrences(of: " ", with: "") ?? ""
// Combine the new string with the existing text without spaces
let newText = (textWithoutSpaces as NSString).replacingCharacters(in: range, with: string)
// Insert spaces every 4 characters
let formattedText = newText.chunkFormatted(withChunkSize: 4, separator: " ")
// Update the text field's text
textField.text = formattedText
// Since you're updating the text manually, return false to prevent default behavior
return false
}
}
extension String {
func chunkFormatted(withChunkSize chunkSize: Int, separator: String) -> String {
return stride(from: 0, to: count, by: chunkSize).map {
let start = index(startIndex, offsetBy: $0)
let end = index(start, offsetBy: chunkSize, limitedBy: endIndex) ?? endIndex
return String(self[start..<end])
}.joined(separator: separator)
}
}