Swift 不渲染此视图

问题描述 投票:0回答:1
import SwiftUI

public struct ExpandingTextFieldView: View {
    @Binding var text: String
    let placeholder: String
    @FocusState private var isFocused: Bool

    public init(
        text: Binding<String>,
        placeholder: String = "Enter your text here..."
    ) {
        self._text = text
        self.placeholder = placeholder
    }

    public var body: some View {
        TextEditor(text: $text)
            .fixedSize(horizontal: false, vertical: true)
            .focused($isFocused)
            .onAppear {
                text = text.isEmpty ? placeholder : text
            }
            .onChange(of: isFocused) { _, focus in
                text = focus && text == placeholder ? "" : (!focus && text.isEmpty ? placeholder : text)
            }
    }
}

#Preview {
    @State @Previewable var textValue = ""
    ExpandingTextFieldView(
        text: $textValue,
        placeholder: "Type here..."
    )
    .overlay(RoundedRectangle(cornerRadius: 8).stroke(.gray.opacity(0.5), lineWidth: 2))
}

当 textValue 为“”时,视图渲染良好,显示占位符,并且我可以编辑该值。

当 textValue 设置为其他值时,视图根本不会渲染。我什至不知道如何调试或找出这样的事情出了什么问题。谢谢您的帮助!

swift swiftui
1个回答
0
投票

我最终这样做是有效的,但我仍然想知道为什么原来的解决方案不起作用。

import SwiftUI

public struct ExpandingTextFieldView: View {
    @Binding var text: String
    let placeholder: String

    public init(
        text: Binding<String>,
        placeholder: String = "Enter your text here..."
    ) {
        self._text = text
        self.placeholder = placeholder
    }

    public var body: some View {
        TextField(placeholder, text: $text, axis: .vertical)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.