TextEditor in SwiftUI

458 阅读1分钟

在 SwiftUI 中,TextEditor 是用于编辑和显示多行文本的组件。使用起来也很简单,和TextField有很多类似的地方。但是TextField天然支持多行文本输入。

以下是一个基本的UI搭建示例,这里主要是一个TextEditor和一个Button,当我们点击Button时,就会把TextEditor里面的值赋值给下面显示的Text

image.png 点击后:

image.png

struct TextEditorSample: View {
    @State var textEditorText: String = ""
    @State var resultText: String = ""
    
    var color = #colorLiteral(red: 0.9490196078, green: 0.9450980392, blue: 0.9607843137, alpha: 1)
    
    var body: some View {
        NavigationView {
            VStack {
                TextEditor(text: $textEditorText)
                    .foregroundColor(.black)
                    .multilineTextAlignment(.leading)
                    .frame(height: 240)
                    .colorMultiply(Color(uiColor: color))
                    .cornerRadius(10)
                
                Button {
                    resultText = textEditorText
                } label: {
                    Text("Save".uppercased())
                        .foregroundColor(.white)
                        .font(.headline)
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(Color.blue.cornerRadius(10))
                }
                
                Text(resultText)
                Spacer()
            }
            .padding(.horizontal)
            .navigationTitle("TextEditor sample")
        }
    }
}

值得注意的是:设置TextEditor时需要使用colorMultiply 方法,使用background来设置不会有作用。

好了TextEditor很简单,就这么多了

大家有什么看法呢?欢迎留言讨论。
公众号:RobotPBQ