View — TextEditor
This article is extracted from the chat log with AI. Please identify it with caution.

TextEditor 是 SwiftUI 中用于处理多行文本输入的组件,适用于需要用户输入较长文本的场景。以下是其使用方式、适用场景及案例详解:


一、基本使用方式 #

  1. 基础语法

    struct ContentView: View {
        @State private var text: String = ""
    
        var body: some View {
            TextEditor(text: $text)
                .font(.body)
                .padding()
        }
    }
    

    • 使用 @State 绑定文本内容,实时响应用户输入。 • 支持常见修饰符(如字体、边距)。

  2. 高级初始化参数(iOS 16+):

    TextEditor(text: $text, axis: .vertical)  // 垂直方向滚动
      .lineLimit(5...)  // 最小5行,最多不限(macOS 适用)
      .presentationCornerRadius(10)  // 圆角
      .scrollIndicators(.visible)  // 显示滚动条
    
  3. 添加占位符(Placeholder):

    ZStack(alignment: .topLeading) {
        if text.isEmpty {
            Text("请输入内容...")
                .foregroundColor(.gray)
                .padding(.top, 8)
                .padding(.leading, 5)
        }
        TextEditor(text: $text)
    }
    

二、适用场景 #

  1. 多行文本输入: • 长文本场景:笔记、评论、文章编辑、表单描述等。 • 替代 TextField(适合单行输入)。

  2. 需要动态扩展的输入框: • 结合 axis: .vertical(iOS 16+)实现高度自适应。

  3. 富文本编辑: • 通过 NSAttributedString 自定义样式(需结合 UIKit 的 UITextView)。


三、使用案例 #

案例1:社交应用评论框 #

struct CommentView: View {
    @State private var comment: String = ""
    
    var body: some View {
        VStack {
            TextEditor(text: $comment)
                .frame(minHeight: 100, maxHeight: 200)
                .padding()
                .background(RoundedRectangle(cornerRadius: 10).stroke(Color.gray))
            
            Button("提交") {
                // 处理评论提交
            }
        }
    }
}

• 特点:限制最小/最大高度,添加边框,支持滚动。

案例2:自适应高度的输入框(iOS 16+) #

TextEditor(text: $text, axis: .vertical)
    .lineLimit(5, reservesSpace: true)  // 默认显示5行,留出空间

• 输入超过5行时自动滚动,适合聊天输入框。

案例3:带字数统计的笔记编辑器 #

struct NoteEditor: View {
    @State private var content: String = ""
    private var wordCount: Int { content.count }
    
    var body: some View {
        VStack {
            TextEditor(text: $content)
                .font(.system(.body, design: .serif))
                .border(Color.blue, width: 1)
            
            Text("字数:\(wordCount)")
                .foregroundColor(.gray)
        }
        .toolbar {
            ToolbarItem(placement: .keyboard) {
                Button("完成") { /* 收起键盘 */ }
            }
        }
    }
}

• 特点:自定义字体、边框,显示实时字数,键盘工具栏添加操作按钮。


四、注意事项 #

  1. 样式自定义: • iOS 默认无边框,需手动添加(如 background + RoundedRectangle)。 • 通过 .scrollContentBackground(.hidden)(iOS 16+)隐藏默认背景。

  2. 键盘控制

    TextEditor(text: $text)
        .keyboardType(.twitter)  // 指定键盘类型
        .autocorrectionDisabled()  // 关闭自动修正
        .textInputAutocapitalization(.words)  // 首字母大写
    

3性能优化**: • 避免在频繁更新的闭包中处理文本(如实时高亮),考虑使用 onChange 延迟处理。


五、跨平台差异 #

iOS:默认无边框,需手动装饰。 • macOS:自带边框,支持更多行数控制(如 lineLimit(5...))。 • 版本要求:最低支持 iOS 13、macOS 11,部分功能需 iOS 16+。

通过灵活运用 TextEditor,可快速构建符合平台习惯的文本输入界面。

本文共 993 字,创建于 Apr 10, 2025
相关标签: Xcode, SwiftUI, ByAI