0

因此,我制作了一个成功的动态 TextEditor,但是当我尝试组合视图时,它会与其他元素重叠,并且在您键入时不再扩展。我很确定这与 Geometry Reader 有关,但如果没有它,我不知道该怎么做。谢谢!

ScrollView {
    
    GeometryReader { geometry in
        
        
        VStack{
            
            
            ZStack(alignment: .leading) {
                
                Text(text).foregroundColor(.clear)
                .padding(14)
                .font(.custom("Times", size: 14))
                .background(GeometryReader {
                    Color.clear.preference(key: viewheightkey3.self, value: $0.frame(in: .local).size.height)
                })
                .frame(width: geometry.size.width * 0.9)
                
                TextEditor(text: $text)
                .padding(6)
                .foregroundColor(.white)
                .frame(width: geometry.size.width * 0.9)
                .frame(height: height)
                .frame(minHeight: 100)
                .background(Color.black)
                
            }
            
            .padding(20)
            .onPreferenceChange(viewheightkey3.self) { height = $0 }
            
        }
        
        
    }
    
    struct viewheightkey3: PreferenceKey {
        static var defaultValue: CGFloat { 0 }
        static func reduce(value: inout Value, nextValue: () -> Value) {
            value = value + nextValue()
        }
    }
4

1 回答 1

1

如果您可以摆脱框架宽度的东西(您可以只做一些水平填充来代替它),这似乎有效:

struct ContentView: View {
    @State private var textEditorHeight : CGFloat = 100
    @State private var text = "Testing text. Hit a few returns to see what happens"
    
    var body: some View {
        ScrollView {
            VStack{
                Text("This should be above")
                ZStack(alignment: .leading) {
                    Text(text)
                        .font(.custom("Courier", size: 24))
                        .foregroundColor(.clear)
                        .padding(14)
                        .background(GeometryReader {
                            Color.clear.preference(key: ViewHeightKey.self,
                                                   value: $0.frame(in: .local).size.height)
                        })
                    
                    TextEditor(text: $text)
                        .font(.custom("Courier", size: 24))
                        .padding(6)
                        .frame(height: textEditorHeight)
                        .background(Color.black)
                }
                .padding(20)
                .onPreferenceChange(ViewHeightKey.self) { textEditorHeight = $0 }
                
                Text("This should be below the text field")
            }
        }
    }
}

struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout Value, nextValue: () -> Value) {
        value = value + nextValue()
    }
}

我并没有真正改变你所做的任何根本性的事情。大多数情况下只是摆脱了外部GeometryReaderframe依赖于从外部传入的高度PreferenceKey

于 2021-03-05T05:33:59.123 回答