You need to enable JavaScript to run this app. SwiftUI自定义TextField编程修改内容不触发textViewDidChange修复
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI自定义TextField编程修改内容不触发textViewDidChange修复

自定义UITextView编程更新文本问题修复

问题根源

  • 占位符判断逻辑错误:重置文本时设置为空格" ",但占位符显示判断仅用text.isEmpty,空格不属于空字符串,导致占位符直接隐藏。
  • 编程修改uiView.text时,系统不会自动触发textViewDidChange代理,原有高度计算、绑定同步逻辑失效,后续输入状态紊乱。
  • Coordinator中存储的CustomTextFieldRep是值类型快照,不会随代表的更新自动同步,代理回调时操作的是旧绑定引用。
  • UITextView默认开启滚动,未禁用滚动导致自适应高度逻辑失效,长文本输入时内容丢失。
  • 聚焦绑定实现错误:原nameFocusBinding直接对Binding<Focus?>调用isEqual(to:),返回Bool而非Binding<Bool>,聚焦逻辑完全失效。
  • 占位符变量未声明为状态属性:修改placeholderName后不会触发UI刷新。

修复后完整代码

自定义TextField组件代码

import SwiftUI

struct CustomTextField: View {
    var title: String
    @Binding var text: String
    var isFocused: Binding<Bool>?

    @State var height: CGFloat = 20

    var onCommit: (() -> ())?

    init(_ title: String, text: Binding <String>, isFocused: Binding<Bool>? = nil, onCommit: (() -> ())? = nil){
        self.title = title
        self._text = text
        self.isFocused = isFocused
        self.onCommit = onCommit
    }
    var body: some View {
        ZStack(alignment: .topLeading){
            Text(title)
                .foregroundColor(Color.secondary.opacity(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? 0.5 : 0))
                .animation(nil)
            CustomTextFieldRep(text: $text, isFocused: isFocused, height: $height, onCommit: onCommit)
                .frame(height: height)
        }
    }
}

struct CustomTextFieldRep: UIViewRepresentable{

    @Binding var text: String
    var isFocused: Binding<Bool>?
    @Binding var height: CGFloat
    var onCommit: (() -> ())?

    func makeUIView(context: Context) -> UITextView {
        let uiView = UITextView()
        
        uiView.font = UIFont.preferredFont(forTextStyle: .body)
        uiView.backgroundColor = .clear
        uiView.text = text
        uiView.delegate = context.coordinator
        uiView.textContainerInset = .zero
        uiView.textContainer.lineFragmentPadding = 0
        uiView.isScrollEnabled = false
        
        return uiView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        context.coordinator.rep = self
        
        if uiView.text != text{
            uiView.text = text
            context.coordinator.textViewDidChange(uiView)
        }
        
        if let isFocused = isFocused?.wrappedValue{
            if isFocused && !uiView.isFirstResponder{
                uiView.becomeFirstResponder()
            }else if !isFocused && uiView.isFirstResponder{
                uiView.resignFirstResponder()
            }
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(rep: self)
    }

    class Coordinator: NSObject, UITextViewDelegate{
        
        var rep: CustomTextFieldRep
        
        internal init(rep: CustomTextFieldRep){
            self.rep = rep
        }
        
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            if let onCommit = rep.onCommit, text == "\n"{
                onCommit()
                return false
            }
            
            return true
        }
        
        func textViewDidChange(_ textView: UITextView) {
            rep.text = textView.text
            
            let size = textView.sizeThatFits(CGSize(width: textView.frame.width, height: CGFloat.greatestFiniteMagnitude))
            rep.height = size.height
        }
        
        func textViewDidBeginEditing(_ textView: UITextView) {
            rep.isFocused?.wrappedValue = true
        }
        
        func textViewDidEndEditing(_ textView: UITextView) {
            rep.isFocused?.wrappedValue = false
        }
    }
}

使用页修复代码

struct ExerciseView: View{
    @ObservedObject private var addUebungVM = AddÜbungViewModel()
    enum Focus{
        case name, beschreibung
    }

    @State var focus: Focus? = .name
    @State private var placeholderName = NSLocalizedString("übungNamePlaceholder", comment: "")

    var nameFocusBinding: Binding<Bool>{
        Binding(
            get: { focus == .name },
            set: { newValue in
                if newValue {
                    focus = .name
                } else if focus == .name {
                    focus = nil
                }
            }
        )
    }

    var beschreibungFocusBinding: Binding<Bool>{
        Binding(
            get: { focus == .beschreibung },
            set: { newValue in
                if newValue {
                    focus = .beschreibung
                } else if focus == .beschreibung {
                    focus = nil
                }
            }
        )
    }

    var body: some View{
        CustomTextField(placeholderName, text: $addUebungVM.übungName, isFocused: nameFocusBinding, onCommit: saveNewÜbung)
          .alignmentNewExercise()
          .styleTextField()
    }

    private func saveNewÜbung(){
        if !addUebungVM.übungName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty{
            DispatchQueue.main.async{
                addUebungVM.übungName = ""
                addUebungVM.übungBeschreibung = ""
                placeholderName = NSLocalizedString("nächsteÜbungString", comment: "")
                focus = .name
            }
        }
    }
}

关键修复点说明

  • 占位符判断:增加trimmingCharacters(in: .whitespacesAndNewlines)过滤,全空格/换行也会被判定为内容为空,正常显示占位符。
  • 代理逻辑复用:编程修改uiView.text后直接调用textViewDidChange,统一处理绑定同步、高度计算,避免重复代码导致的逻辑不一致。
  • Coordinator同步:每次updateUIView时更新coordinator.rep为最新的代表实例,解决值类型快照导致的代理回调引用旧绑定的问题。
  • 滚动禁用:设置isScrollEnabled = false让UITextView根据内容高度自动调整,不会出现长文本被滚动隐藏的问题。
  • 聚焦绑定重写:使用标准Binding(get:set:)实现双向绑定,解决原实现返回值类型错误导致的聚焦逻辑失效问题。
  • 状态属性补充:placeholderName声明为@State,修改后会触发UI刷新。
  • 重置逻辑优化:清空文本时设置为空字符串而非空格,避免无效的全空格内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.06 01:45:02