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

如何在UITextView中实现密码保护:用*或符号隐藏全部输入字符

在UITextView中实现密码隐藏(用*或自定义符号)

当然可以搞定!虽然UITextView不像UITextField那样自带secureTextEntry属性,但我们可以通过两种实用方式模拟密码隐藏效果,完全满足你必须使用UITextView的需求。

方法一:分离真实内容与显示内容(简单直接)

核心思路是用一个变量悄悄存储用户输入的真实密码,UITextView只展示对应的*(或你指定的任意符号)。具体步骤如下:

  1. 在你的ViewController中声明一个变量用于保存真实密码:
private var realPassword = ""
  1. 给UITextView设置代理,并实现代理方法接管输入逻辑:
extension YourViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 处理删除操作:输入为空说明用户按了删除键
        if text.isEmpty {
            if !realPassword.isEmpty {
                realPassword.removeLast()
            }
            // 更新显示的星号数量
            textView.text = String(repeating: "*", count: realPassword.count)
            return false // 阻止系统默认的文本修改行为
        }
        
        // 处理普通输入:把输入字符追加到真实密码,再更新显示内容
        realPassword += text
        textView.text = String(repeating: "*", count: realPassword.count)
        return false
    }
}

注意:要记得提前给textView设置delegate = self,否则代理方法不会生效。

方法二:保留光标位置的优化方案

上面的方法有个小瑕疵——光标会一直固定在文本末尾,体验不够自然。如果想要光标跟着输入位置正常移动,可以用NSAttributedText实现更流畅的效果:

  1. 同样先声明存储真实密码的变量:
private var realPassword = ""
  1. 实现textViewDidChange代理方法:
extension YourViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        // 保存当前真实文本和光标位置
        guard let inputText = textView.text else { return }
        realPassword = inputText
        let cursorPosition = textView.selectedRange
        
        // 生成对应长度的星号文本替换显示
        let displayText = String(repeating: "*", count: inputText.count)
        textView.attributedText = NSAttributedString(string: displayText)
        
        // 恢复光标位置,让用户感觉和正常输入无差别
        textView.selectedRange = cursorPosition
    }
}

额外注意事项

  • 禁用UITextView的拼写检查和自动更正,避免干扰输入:
textView.autocorrectionType = .no
textView.spellCheckingType = .no
textView.autocapitalizationType = .none
  • 自定义隐藏符号:直接把代码里的"*"换成你想要的字符即可,比如"●"或"■"
  • 限制密码长度:在代理方法里判断realPassword.count是否超过阈值,超过则拒绝输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:58:01