swift 如何更改TextEditor的背景色,如TextField

wfypjpf4  于 2023-08-02  发布在  Swift
关注(0)|答案(3)|浏览(166)
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的背景色,我试过了:

  • .foregroundColor更改了文本颜色而不是背景颜色;
  • .background只改变了周围的背景颜色,而不是整个TextEditor,如下图所示:

x1c 0d1x的数据

rbpvctlc

rbpvctlc1#

将这一行添加到TextEditor

.scrollContentBackground(.hidden) // <- Hide it

字符串

ajsxfq5m

ajsxfq5m2#

UITextViewTextEditor的基底类别。因此,在初始化struct时,需要将UITextView的背景颜色更改为clear,然后可以将任何颜色设置为背景。

struct ContentView: View {
    init() {
        UITextView.appearance().backgroundColor = .clear
    }
}

字符串

zazmityj

zazmityj3#

您可以创建适用于所有iOS版本的修改器

func transparentScrolling() -> some View {
    if #available(iOS 16.0, *) {
        return scrollContentBackground(.hidden)
    } else {
        return onAppear {
            UITextView.appearance().backgroundColor = .clear
        }
    }
}

字符串
然后将其添加到TextFieldTextEditor

TextEditor(text: $textString)
.multilineTextAlignment(.leading)
.foregroundColor(.primaryText)
.frame(height: 75)
.transparentScrolling()

相关问题