在所附的代码示例中,我的TextField获得了很多额外的顶部间距。如果我将内容更改为仅一行,说“内容”,那么它就很贴合。如何获得多行文本与单行相同的紧缩行为?
预览和代码是使用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"
答案 0 :(得分:1)
似乎没有直接的论据来正确管理多行填充。他们可能正在发展中。但是,以下内容将为您提供预期的解决方案。
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
以实现所需的功能。希望它也对您有用。