SwiftUI:如何使 TextField 适合多行内容?

SwiftUI: How do I make TextField fit multi-line content?

在附加的代码示例中,我的 TextField 中有很多额外的顶部间距。如果我将内容更改为只有一行,比如 "content",那么它就很合适。如何获得单行文本与多行文本相同的紧身行为?

预览和代码是使用 Xcode 11.1 / Swift 5.1

制作的
import SwiftUI

struct TextFieldDemo: View {
    var content: Binding<String>

    init(content: Binding<String>) {
        self.content = content
    }

    var body: some View {
        TextField("Custom placeholder", text: content)
            .background(Color.yellow)
    }
}

#if DEBUG
struct TextInputRowPreviews: PreviewProvider {

    static var previews: some View {
        let content = "content\ncontent\ncontent\ncontent\ncontent\ncontent"
        return TextFieldDemo(content: .constant(content))
                .previewLayout(.sizeThatFits)
    }
}
#endif

这是我将 "let content" 行更改为

的示例
let content = "content"

似乎没有直接的论据来正确管理多行填充。他们可能不发达。但以下内容将为您提供符合您预期的直接解决方法。

extension String{
    var extraLines : String{ get{
         return self +  String(repeating:"\n",  count: self.components(separatedBy:  "\n").count - 1)
    }}
 }


struct TextFieldDemo: View {
var content: Binding<String>

init(content: Binding<String>) {
    self.content = content
}

@State var height : CGFloat? //current height

let constHeightRatio : CGFloat = 0.55 //use for assembly with other fonts.
let defaultHeight : CGFloat = 250 //use for assembly with other views.

var body: some View {
    TextField("Custom placeholder", text: content).environment(\.multilineTextAlignment, .center).alignmentGuide(.bottom) { (ViewDimensions) -> CGFloat in
        if self.height == nil {self.height = ViewDimensions.height}
            return  ViewDimensions.height
    }.frame( height: (height ?? defaultHeight) * constHeightRatio, alignment: .bottom).background(Color.yellow)
}
}



#if DEBUG
struct TextInputRowPreviews: PreviewProvider {

static var previews: some View {
    let content = "content\ncontent\ncontent".extraLines
    return
         TextFieldDemo(content: .constant(content))
}
}
#endif

这对于单视图来说效果很好。如果需要视图组装(与其他堆叠视图等),您可以调整 defaultHeight and/or constHeightRatio 来实现您想要的。希望它也适合你。