Yoel Jimenez del valle
Yoel Jimenez del valle

Reputation: 1278

how to add a string after each comma in UITextfield

Im lookin a way to add # at the beginig of each word written in uiTextField with swift, i tryes to check using this code

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
   if  textField.text!.first != "#" {
        print(textField.text!.first)
        print(textField.text!)
        textField.text = ""
   }
}

but the firsrt character is nil when the input on keyboard is # so what should be the way to achive this having all the words begins with # and separated by ,

Upvotes: 0

Views: 460

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

You can make it easier checking the text after editing changed control event and clean your string when the user types a space after each word. You can subclass your UITextField and it should look something like this:

class TagsField: UITextField, UITextFieldDelegate {
    override func didMoveToSuperview() {
        delegate = self
        keyboardType = .alphabet
        autocapitalizationType = .none
        autocorrectionType = .no
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        prepareString()
        if text!.hasSuffix(", #") { text!.removeLast(3) } // clean the residue on end
        resignFirstResponder()
        return false
    }
    func prepareString() {
        text = text!.components(separatedBy: CharacterSet.letters.inverted)   // filtering non letters and grouping words
                .filter{!$0.isEmpty}           // filtering empty components
                .map{ "#" + $0 + ", " }        // add prefix and sufix to each word and append # to the end of the string
                .string + "#" 

    }
    override func deleteBackward() {
        let _ = text!.popLast()    // manually pops the last character when deliting
    }
    @objc func editingChanged(_ textField: UITextField) {
        if text!.last == " " {
            prepareString()
        } else if !text!.hasPrefix("#") {  // check if the first word being typed has the # prefix and add it if needed.
            text!.insert("#", at: text!.startIndex)
        }
    }
}

extension Collection where Element: StringProtocol {
    var string: String {
        return String(joined())
    }
}

Upvotes: 1

Related Questions