Search code examples
swiftuitextfielduilabelfunc

textfielddidbegin editing not updating label


My swift code below goal is when the user enters something into textfield tt it reflects it in currentPageLabel. The func that I thought would do this is having no effect. Nothing I enter into the textfield displays on the label. All of my code does not use a storyboard.

var currentPageLabel = UILabel()
var tt = UITextfield()

func textFieldDidBeginEditing(_ textField: UITextField) {
    currentPageLabel.text = tt.text
}

Solution

  • Try this UITextFieldDelegate method:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
        currentPageLabel.text = text
        return true
    }