You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift Xcode中如何在VStack顶部添加UITextView?

解决方案

报错根因

UITextView是UIKit组件,未实现SwiftUI的View协议,无法直接放入VStack等SwiftUI容器中使用,需通过UIViewRepresentable协议封装为SwiftUI兼容的视图类型。

实现步骤

  1. 封装UITextView为SwiftUI可用视图,支持双向文本绑定:
import SwiftUI
import UIKit

struct CustomUITextView: UIViewRepresentable {
    @Binding var text: String
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        // 可按需自定义UITextView属性
        textView.font = .systemFont(ofSize: 16)
        textView.isEditable = true
        textView.isScrollEnabled = true
        textView.delegate = context.coordinator
        return textView
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }
    
    class Coordinator: NSObject, UITextViewDelegate {
        var parent: CustomUITextView
        
        init(parent: CustomUITextView) {
            self.parent = parent
        }
        
        func textViewDidChange(_ textView: UITextView) {
            parent.text = textView.text
        }
    }
}
  1. 将封装好的视图插入VStack对应位置,修改后的业务代码如下:
// 提前声明绑定用状态变量
@State private var ingredients = ""
@State private var textViewContent = ""

VStack {
    Text("Hey")
        .font(.title)
        .foregroundColor(Color.black)
    // 插入UITextView到TextField上方
    CustomUITextView(text: $textViewContent)
        .frame(height: 100) // 按需设置高度
    TextField("Write here", text: $ingredients)
    Button(action: {
        let array = self.ingredients.lowercased().components(separatedBy: " ")
        // 补充业务逻辑
    }) {
        // 补充按钮显示内容
        Text("提交")
    }
}

内容的提问来源于stack exchange,提问作者Lea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 11:54:02