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

Swift 无需点击按钮纯代码实现UITextField空值显红边有内容去红边

Swift 实现UITextField输入内容动态切换边框方案

实现逻辑

通过监听UITextField的.editingChanged编辑事件,实时判断文本内容是否为空,动态调整边框样式,无需额外按钮触发。

完整代码示例

import UIKit

class DemoViewController: UIViewController {
    // 声明目标文本输入框
    private let targetTextField = UITextField()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureTextField()
    }
    
    private func configureTextField() {
        // 基础布局配置
        targetTextField.frame = CGRect(x: 60, y: 150, width: 250, height: 45)
        targetTextField.placeholder = "请输入内容"
        targetTextField.borderStyle = .roundedRect
        // 初始配置红色边框
        targetTextField.layer.borderWidth = 1
        targetTextField.layer.borderColor = UIColor.red.cgColor
        view.addSubview(targetTextField)
        
        // 核心:添加文本变更事件监听
        targetTextField.addTarget(self, action: #selector(updateTextFieldBorder), for: .editingChanged)
    }
    
    /// 动态更新文本框边框
    @objc private func updateTextFieldBorder(_ sender: UITextField) {
        // 判断文本是否为空,可根据需求调整是否过滤空格/换行
        let hasContent = !(sender.text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
        // 有内容时移除红色边框,无内容时恢复
        sender.layer.borderColor = hasContent ? UIColor.clear.cgColor : UIColor.red.cgColor
    }
}

可选调整项

  • 如果需要保留非红色的默认边框,将UIColor.clear.cgColor替换为你的默认边框颜色即可
  • 不需要过滤纯空格输入的话,将判断逻辑改为let hasContent = !(sender.text?.isEmpty ?? true)即可
  • 该方案兼容所有输入操作:手动输入、粘贴内容、删除内容、选中全删都会触发回调,无需额外适配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:06:06