如何将Binding<String>转为String?SwiftUI自定义TextField调用isEmpty解决方案
SwiftUI自定义TextField中Binding判空的最优解决方案
解决该问题的最优方案是直接通过Binding类型内置的wrappedValue属性访问其包裹的实际字符串值,无需额外创建自定义View结构体。
Binding<T>是SwiftUI提供的值包装类型,本身不具备T类型的属性方法,需要通过wrappedValue获取它实际存储的T类型值后再做逻辑判断。你可以直接将原有代码中所有text.isEmpty的位置替换为text.wrappedValue.isEmpty,也可以提前抽取判空结果简化后续代码,修改后的完整实现如下:
func customTextField(placeholder: String, text: Binding<String>) -> some View { // 提前抽取判空结果简化后续重复调用 let isTextEmpty = text.wrappedValue.isEmpty ZStack(alignment: .leading){ if isTextEmpty { VStack { Text(placeholder) .font(.system(size: 14)) .fontWeight(.regular) .foregroundColor(Color(red: 0.5803921568627451, green: 0.5803921568627451, blue: 0.5803921568627451)) .padding() if placeholder == "Your message type here..."{ Spacer() } } } TextField("", text: text) .font(.system(size: 14)) .foregroundColor(.black) .padding() } .frame(height: placeholder == "Your message type here..." ? 170 : 54) .background(RoundedRectangle(cornerRadius: 16).stroke(isTextEmpty ? Color.clear : Color("orange"))) .background(Color.white) .cornerRadius(16) }
上述实现不会出现值缓存问题,绑定的字符串发生变化时当前View会自动刷新,局部常量isTextEmpty也会同步更新。
内容的提问来源于stack exchange,提问作者Vlad Poncea
相关产品推荐
相关产品推荐

