如何在Swift中移除Google Material MDCOutlinedTextField编辑时的占位符
MDCOutlinedTextField 占位符与浮动标签重复问题解决方案
问题根源
两处提示文本重复显示的核心原因是同时配置了MDCOutlinedTextField的浮动标签(label.text)和原生placeholder属性,组件默认不会在进入编辑状态时自动清空原生占位符,因此出现内容重叠。
方案1:使用组件原生能力(推荐)
MDCOutlinedTextField的浮动标签本身就支持替代占位符的交互效果,不需要额外设置原生placeholder,修改代码如下:
func setupGoogleMaterialTextFields(textFields: [MDCOutlinedTextField]) { let containerScheme = MDCContainerScheme() let colorScheme = MDCSemanticColorScheme() colorScheme.primaryColor = UIColor.white colorScheme.onSurfaceColor = UIColor.white containerScheme.colorScheme = colorScheme for textField in textFields { // 保存原占位符内容到浮动标签 textField.label.text = textField.placeholder textField.font = UIFont.myMediumSystemFont(ofSize: 18) // 删掉原生attributedPlaceholder设置,用浮动标签替代占位符 textField.floatingLabelBehavior = .whenEditing textField.containerRadius = 8 textField.sizeToFit() textField.applyTheme(withScheme: containerScheme) } }
该方案交互逻辑:
- 文本框未激活且无内容时,标签显示在输入框内,和普通占位符效果一致
- 进入编辑状态时标签自动上浮为浮动标签,输入区不会残留重复的提示文本
- 完全符合Material Design设计规范,不需要额外写监听逻辑
方案2:保留原占位符样式的修改方法
如果你需要保留自定义的占位符字体、颜色样式,可以通过监听编辑状态动态控制占位符显隐:
- 首先在配置方法中给文本框添加编辑状态监听
func setupGoogleMaterialTextFields(textFields: [MDCOutlinedTextField]) { let containerScheme = MDCContainerScheme() let colorScheme = MDCSemanticColorScheme() colorScheme.primaryColor = UIColor.white colorScheme.onSurfaceColor = UIColor.white containerScheme.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.addTarget(self, action: #selector(textFieldDidBeginEditing(_:)), for: .editingDidBegin) textField.addTarget(self, action: #selector(textFieldDidEndEditing(_:)), for: .editingDidEnd) textField.containerRadius = 8 textField.sizeToFit() textField.applyTheme(withScheme: containerScheme) } }
- 实现监听方法,动态控制占位符显隐
@objc private func textFieldDidBeginEditing(_ textField: MDCOutlinedTextField) { // 进入编辑状态直接清空占位符,避免和浮动标签重叠 textField.attributedPlaceholder = nil } @objc private func textFieldDidEndEditing(_ textField: MDCOutlinedTextField) { // 结束编辑时如果输入框为空,恢复占位符 guard let inputText = textField.text, inputText.isEmpty else { return } textField.attributedPlaceholder = NSAttributedString(string: textField.label.text ?? "", attributes: [.foregroundColor: UIColor.white, .font: UIFont.myMediumSystemFont(ofSize: 16)]) }
内容的提问来源于stack exchange,提问作者Aijaz.Ali90
相关产品推荐
相关产品推荐

