J'ai un textfield
de textfield
avec la gamme de caractères maximum 16, je veux après chaque caractère de 4 caractères ajoutent le caractère ou l'espace et écris ensuite le rest des caractères comme cet échantillon 5022-2222-2222-2222. il y a mon code mais ça ne marche pas, comment faire ça?
if textField.text?.characters.count == 5 { let l = textField.text?.characters.count let atsortingbutedSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: cartNumberTextField.text!) atsortingbutedSsortingng.addAtsortingbute(NSKernAtsortingbuteName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4)) cartNumberTextField.atsortingbutedText = atsortingbutedSsortingng } else if textField.text?.characters.count == 9 { let l = textField.text?.characters.count let atsortingbutedSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: cartNumberTextField.text!) atsortingbutedSsortingng.addAtsortingbute(NSKernAtsortingbuteName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4)) cartNumberTextField.atsortingbutedText = atsortingbutedSsortingng } else if textField.text?.characters.count == 13 { let l = textField.text?.characters.count let atsortingbutedSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: cartNumberTextField.text!) atsortingbutedSsortingng.addAtsortingbute(NSKernAtsortingbuteName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4)) cartNumberTextField.atsortingbutedText = atsortingbutedSsortingng }
Je suis append ce code dans la méthode de plage UITextField
shouldChangeCharactersIn
.
Nous pouvons commencer par implémenter une version Swift 3 de la méthode chunk(n:)
(pour Collection
) de oisdk: s SwiftSequence :
/* Swift 3 version of Github use oisdk:s SwiftSequence's 'chunk' method: https://github.com/oisdk/SwiftSequence/blob/master/Sources/ChunkWindowSplit.swift */ extension Collection { public func chunk(n: IndexDistance) -> [SubSequence] { var res: [SubSequence] = [] var i = startIndex var j: Index while i != endIndex { j = index(i, offsetBy: n, limitedBy: endIndex) ?? endIndex res.append(self[i..<j]) i = j } return res } }
Dans ce cas, l'implémentation de votre formatting personnalisé est un cas simple de création de blocs de 4 caractères et de leur jonction par "-":
func customSsortingngFormatting(of str: Ssortingng) -> Ssortingng { return str.characters.chunk(n: 4) .map{ Ssortingng($0) }.joined(separator: "-") }
Exemple d'utilisation:
print(customSsortingngFormatting(of: "5022222222222222")) // 5022-2222-2222-2222 print(customSsortingngFormatting(of: "50222222222222")) // 5022-2222-2222-22 print(customSsortingngFormatting(of: "5022222")) // 5022-222
Si vous souhaitez utiliser la méthode textField(_:shouldChangeCharactersIn:replacementSsortingng:)
de UITextFieldDelegate
, nous pouvons filterr les séparateurs existants dans la méthode method customSsortingngFormatting(of:)
, ainsi que l'implémenter en tant qu'extension Ssortingng
:
extension Ssortingng { func chunkFormatted(withChunkSize chunkSize: Int = 4, withSeparator separator: Character = "-") -> Ssortingng { return characters.filter { $0 != separator }.chunk(n: chunkSize) .map{ Ssortingng($0) }.joined(separator: Ssortingng(separator)) } }
Et mettre en œuvre la mise à jour contrôlée du champ de text, par exemple comme suit:
let maxNumberOfCharacters = 16 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementSsortingng ssortingng: Ssortingng) -> Bool { // only allow numerical characters guard ssortingng.characters.flatMap({ Int(Ssortingng($0)) }).count == ssortingng.characters.count else { return false } let text = textField.text ?? "" if ssortingng.characters.count == 0 { textField.text = Ssortingng(text.characters.dropLast()).chunkFormatted() } else { let newText = Ssortingng((text + ssortingng).characters .filter({ $0 != "-" }).prefix(maxNumberOfCharacters)) textField.text = newText.chunkFormatted() } return false }
La dernière partie ci-dessus va tronquer les strings collées possibles de l'user (étant donné que tout est numérique), par exemple
// current 1234-1234-123 // user paste: 777777777 /* ^^^^ will not be included due to truncation */ // will result in 1234-1234-1237-7777
Utilisez shouldChangeCharactersIn
comme ceci.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementSsortingng ssortingng: Ssortingng) -> Bool { if textField.text?.characters.count == 4 && ssortingng.characters.count != 0 { textField.text = textField.text! + "-" } else if textField.text?.characters.count == 6 && ssortingng.characters.count == 0 { textField.text = Ssortingng(textField.text!.characters.dropLast()) } else if textField.text?.characters.count == 9 && ssortingng.characters.count != 0 { textField.text = textField.text! + "-" } else if textField.text?.characters.count == 11 && ssortingng.characters.count == 0{ textField.text = Ssortingng(textField.text!.characters.dropLast()) } else if textField.text?.characters.count == 14 && ssortingng.characters.count != 0 { textField.text = textField.text! + "-" } else if textField.text?.characters.count == 16 && ssortingng.characters.count == 0 { textField.text = Ssortingng(textField.text!.characters.dropLast()) } if textField.text?.characters.count == 19 && ssortingng.characters.count != 0 { return false } return true }
Note: J'ai utilisé - (Hyphen)
vous pouvez simplement le replace par Space
si vous voulez de l' Space
au lieu de - (Hyphen)
.