【问题标题】:how to remove place holder text from textfield using Google Material MDCOutlinedTextField in swift?如何在swift中使用Google Material MDCOutlinedTextField从文本字段中删除占位符文本?
【发布时间】:2021-08-31 12:23:03
【问题描述】:

这是我编写的代码,但是当用户在文本字段中但没有文本时,占位符仍然出现在文本字段中,也显示在浮动标签中,当我在此文本字段中时,我只想删除

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.placeholder = ""textField.placeholder = nil吗?
  • 感谢@Alhomaidhi 的提示,我已经添加了 textField 代表,现在一切正常。

标签: ios swift iphone material-components-ios


【解决方案1】:

我已像这样将委托分配给 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)
        textField.delegate = self
    }
}

在分配委托后执行此操作。

    extension youClassName: UITextFieldDelegate {

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

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 2020-11-28
    • 1970-01-01
    • 2015-02-22
    • 2012-12-21
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多