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

SwiftUI PasswordTextField输入时边框无变化,需实现输入高亮无内容复原

SwiftUI自定义PasswordTextField边框不更新问题修复

问题根源

  1. 状态逻辑不一致:边框颜色依赖isTyping变量,但线宽却用isFocused || text.count>0判断,两者状态不同步,导致边框显示异常
  2. 错误的状态重置:失去焦点时强制把isTyping设为false,但此时如果文本不为空,边框应该保持深色状态,不该被重置
  3. 冗余的状态监听:手动监听文本变化维护isTyping完全没必要,SwiftUI的状态驱动可以自动处理

修正后的代码

struct PasswordTextField: TextFieldFactory {
    @FocusState private var isFocused: Bool
    @Binding var text: String

    // 统一判断边框激活状态
    private var shouldShowActiveBorder: Bool {
        isFocused || !text.isEmpty
    }

    func createTextField(placeholder: String) -> some View {
        ZStack {
            SecureField(placeholder, text: $text)
                .clearButton(text: $text)
                .padding(.horizontal, 13)
                .padding(.vertical, 14)
                .background(
                    RoundedRectangle(cornerRadius: 14)
                        .fill(AppColors.light80)
                        .overlay(
                            RoundedRectangle(cornerRadius: 14)
                                .stroke(
                                    shouldShowActiveBorder ? AppColors.dark100 : AppColors.light80,
                                    lineWidth: shouldShowActiveBorder ? 1.2 : 0
                                )
                        )
                )
                .frame(width: 348, height: 52)
                .foregroundColor(AppColors.dark100)
                .font(Font.Everett.Regular.body)
                .focused($isFocused)
        }
    }
}

import SwiftUI

protocol TextFieldFactory {
    associatedtype TextFieldType: View
    func createTextField(placeholder: String) -> TextFieldType
}

关键修改点

  • 删掉了多余的isTyping状态,用计算属性shouldShowActiveBorder统一控制边框的颜色和线宽,确保逻辑完全同步
  • 移除了冗余的onChange监听,文本变化或焦点切换时,计算属性会自动更新,无需手动维护状态
  • 实现了预期效果:输入框有焦点或文本不为空时,显示1.2pt的深色边框;文本清空且失去焦点时,恢复初始的0线宽状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:53:16