SwiftUI:如何使TextField适合多行内容? [英] SwiftUI: How do I make TextField fit multi-line content?
问题描述
在所附的代码示例中,我的TextField获得了很多额外的顶部间距.如果我将内容更改为仅一行,说内容",那么它就很贴合.如何获得多行文本与单行相同的紧缩行为?
In the attached code example I get a lot of extra top-spacing in my TextField. If I change the content to only be a single line, say "content", then it fits snugly. How can I get the same tight-fitting behaviour the single line has for a multi-line text?
预览和代码是使用Xcode 11.1/Swift 5.1制作的
Previews and code were made with 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"行更改为
Here is the example if I change the "let content" line to
let content = "content"
推荐答案
似乎没有直接的参数可以正确管理多行填充.他们可能正在发展中.但是以下内容将为您提供一个预期的解决方法.
It seems there's no direct argument to manage multiline padding correctly. They are maybe underdevelopping. But the following will give you a straight workaround solution to what you are expecting.
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
和/或 constHeightRatio
以实现所需的功能.希望它也对您有用.
This works fine for single view. If view assembly is required (with other stacking views, etc), you may adjust defaultHeight
and/or constHeightRatio
to achieve what you want. Hopefully it works for you too.
这篇关于SwiftUI:如何使TextField适合多行内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!