You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何使用MDCOutlinedTextField实现带浮动占位符的外描边输入框?

问题解决方案

1. 浮动占位符缺失、输入框高度偏小修复

MDCOutlinedTextField 已经废弃了原 MDCTextInputController 相关逻辑,所有样式配置直接操作组件本身即可,无需额外初始化控制器。修复步骤如下:

  • 首先在 Storyboard 中给 MDCOutlinedTextField 添加高度约束,设置固定值为 50,也可通过代码添加约束。
  • 在 viewDidLoad 中完成占位符、样式配置,只要正确设置 placeholder 属性,输入内容时占位符会自动上浮为浮动标签。
    代码示例:
import UIKit
import MaterialComponents.MaterialTextControls_OutlinedTextFields

class LoginVC: UIViewController {
    @IBOutlet weak var emailTF: MDCOutlinedTextField!
    @IBOutlet weak var passwordTF: MDCOutlinedTextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 配置邮箱输入框
        emailTF.placeholder = "请输入邮箱"
        // 设置描边颜色
        emailTF.setOutlineColor(.lightGray, for: .normal)
        emailTF.setOutlineColor(.green, for: .editing)
        // 设置浮动标签颜色
        emailTF.setFloatingLabelColor(.lightGray, for: .normal)
        emailTF.setFloatingLabelColor(.green, for: .editing)
        // 设置普通状态占位符颜色
        emailTF.setNormalLabelColor(.lightGray, for: .normal)
        
        // 配置密码输入框
        passwordTF.placeholder = "请输入密码"
        passwordTF.setOutlineColor(.lightGray, for: .normal)
        passwordTF.setOutlineColor(.green, for: .editing)
        passwordTF.setFloatingLabelColor(.lightGray, for: .normal)
        passwordTF.setFloatingLabelColor(.green, for: .editing)
        passwordTF.setNormalLabelColor(.lightGray, for: .normal)
        passwordTF.isSecureTextEntry = true
        
        // 代码添加高度约束(如果没在Storyboard设置的话打开下面注释)
        // emailTF.heightAnchor.constraint(equalToConstant: 50).isActive = true
        // passwordTF.heightAnchor.constraint(equalToConstant: 50).isActive = true
    }
}

2. 密码输入框显隐按钮实现

利用 MDCOutlinedTextField 原生的 trailingView 属性添加右侧按钮即可,代码如下:
在 viewDidLoad 中补充密码框配置:

// 配置密码显隐按钮
let togglePwdBtn = UIButton(type: .custom)
// 可替换为自定义切图
togglePwdBtn.setImage(UIImage(systemName: "eye.slash"), for: .normal)
togglePwdBtn.setImage(UIImage(systemName: "eye"), for: .selected)
togglePwdBtn.tintColor = .lightGray
togglePwdBtn.addTarget(self, action: #selector(togglePasswordVisible), for: .touchUpInside)
togglePwdBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
// 设置右侧视图及显示规则
passwordTF.trailingView = togglePwdBtn
passwordTF.trailingViewMode = .always
// 调整右侧视图内边距,避免贴边
passwordTF.trailingEdgePadding = 10

新增点击事件方法:

@objc private func togglePasswordVisible(_ sender: UIButton) {
    sender.isSelected.toggle()
    passwordTF.isSecureTextEntry = !sender.isSelected
}

内容的提问来源于stack exchange,提问作者User123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:54:08