如何像TextField一样修改SwiftUI中TextEditor的背景颜色
SwiftUI TextEditor 背景颜色修改问题解决
问题描述
修改TextEditor背景颜色时遇到以下问题:
- 使用
.foregroundColor仅改变文本颜色,无法修改背景; - 使用
.background仅改变TextEditor组件外围的背景色,编辑区域的默认背景仍未改变,效果如下:
相关代码:
struct TextView: View { @State private var textInput2: String = "" var body: some View { ScrollView{ VStack(spacing: 24){ TextField("", text: $textInput2) .font(.body) .foregroundColor(.gray) .padding() .frame(height: 142) .background(Color("3")) .cornerRadius(20) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(Color.gray.opacity(0.5), lineWidth: 2) ) TextEditor(text: $textInput2) .textFieldStyle(PlainTextFieldStyle()) .font(.body) .foregroundColor(.gray) .padding() .background(Color("3")) .frame(height: 142) .cornerRadius(20) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(Color.gray.opacity(0.5), lineWidth: 2) ) } .padding(.horizontal) } } }
解决方法
TextEditor底层基于UITextView,默认带有系统背景色,直接用SwiftUI的.background无法覆盖编辑区域的背景。需要先将底层UITextView的背景设为透明,再设置SwiftUI的背景色。
方法1:全局设置(适用于整个App)
在App的初始化方法里添加代码,全局移除TextEditor的默认背景:
@main struct YourApp: App { init() { UITextView.appearance().backgroundColor = .clear } var body: some Scene { WindowGroup { TextView() } } }
设置完成后,原有TextEditor代码中的.background(Color("3"))就能完全覆盖整个编辑区域的背景。
方法2:局部设置(无需第三方库)
用ZStack将TextEditor放在自定义背景层上方,同时隐藏TextEditor的默认背景:
ZStack { Color("3") .cornerRadius(20) TextEditor(text: $textInput2) .textFieldStyle(PlainTextFieldStyle()) .font(.body) .foregroundColor(.gray) .padding() .frame(height: 142) .background(Color.clear) // 设为透明让底层背景显示 } .overlay( RoundedRectangle(cornerRadius: 20) .stroke(Color.gray.opacity(0.5), lineWidth: 2) )
方法3:局部设置(用第三方库精细化处理)
若需要针对单个TextEditor精确修改,可导入Introspect库(通过Swift Package Manager添加),然后修改TextEditor代码:
TextEditor(text: $textInput2) .textFieldStyle(PlainTextFieldStyle()) .font(.body) .foregroundColor(.gray) .padding() .background(Color("3")) .frame(height: 142) .cornerRadius(20) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(Color.gray.opacity(0.5), lineWidth: 2) ) .introspectTextView { textView in textView.backgroundColor = .clear }
内容的提问来源于stack exchange,提问作者T-BM
相关产品推荐
相关产品推荐

