how to remove place holder text from textfield using Google Material MDCOutlinedTextField in swift?

344 Views Asked by At

here is the code I wrote but when the user is in text field but there is no text still place holder appears in textfield in also showing in the floating label I just want to remove when I am inside this textfield

func setupGoogleMaterialTextFields(textFields: [MDCOutlinedTextField]) {
    let containerShceme = MDCContainerScheme()
    let colorScheme = MDCSemanticColorScheme()
    colorScheme.primaryColor = UIColor.white
    colorScheme.onSurfaceColor = UIColor.white
    containerShceme.colorScheme = colorScheme
    for textField in textFields {
        textField.label.text = textField.placeholder 
        textField.font = UIFont.myMediumSystemFont(ofSize: 18)

        textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder ?? "",
                                                             attributes: [NSAttributedString.Key.foregroundColor: UIColor.white,
                                                                          NSAttributedString.Key.font: UIFont.myMediumSystemFont(ofSize: 16)])
        textField.containerRadius = 8
        textField.sizeToFit()
        textField.applyTheme(withScheme: containerShceme)
    }
}
1

There are 1 best solutions below

0
Aijaz.Ali90 On

I have assigned the delegate to the textField like this.

func setupGoogleMaterialTextFields(textFields: [MDCOutlinedTextField]) {
    let containerShceme = MDCContainerScheme()
    let colorScheme = MDCSemanticColorScheme()
    colorScheme.primaryColor = UIColor.white
    colorScheme.onSurfaceColor = UIColor.white
    containerShceme.colorScheme = colorScheme
    for textField in textFields {
        textField.label.text = textField.placeholder 
        textField.font = UIFont.myMediumSystemFont(ofSize: 18)

        textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder ?? "",
                                                             attributes: [NSAttributedString.Key.foregroundColor: UIColor.white,
                                                                          NSAttributedString.Key.font: UIFont.myMediumSystemFont(ofSize: 16)])
        textField.containerRadius = 8
        textField.sizeToFit()
        textField.applyTheme(withScheme: containerShceme)
        textField.delegate = self
    }
}

After Assigning the Delegate do this.

    extension youClassName: UITextFieldDelegate {

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.text?.isEmpty ?? false {
            textField.placeholder = nil
        }
    }
}