Extracted TextWithScrollView

This commit is contained in:
dankito 2020-09-27 03:10:15 +02:00
parent 8df816c091
commit 974e093304
2 changed files with 78 additions and 36 deletions

View File

@ -26,43 +26,8 @@ struct LabelledValue: View {
Spacer() Spacer()
if textFitsIntoAvailableSpace { TextWithScrollView(value)
valueText
} }
else {
ScrollView(.horizontal) {
valueText
}
}
}
}
private var valueText: some View {
return Text(value)
.detailForegroundColor()
.background(
// Render the limited text and measure its size
Text(value).lineLimit(1)
.background(GeometryReader { availableSpace in
ZStack {
// Render the text without restrictions and measure its size
Text(self.value)
.background(GeometryReader { requiredSpace in
// And compare the two
Color.clear.onAppear {
self.textFitsIntoAvailableSpace = self.textFitsIntoAvailableSpace == false ? false : availableSpace.size.width >= requiredSpace.size.width
}
})
}
.frame(width: .greatestFiniteMagnitude)
})
.hidden() // Hide the background
)
} }
} }
@ -75,3 +40,12 @@ struct LabelledValue_Previews: PreviewProvider {
} }
} }
extension LabelledValue {
init(_ label: LocalizedStringKey, _ value: String?) {
self.init(label, value ?? "")
}
}

View File

@ -0,0 +1,68 @@
import SwiftUI
struct TextWithScrollView: View {
private let value: LocalizedStringKey
@State private var textFitsIntoAvailableSpace = true
init( _ value: LocalizedStringKey) {
self.value = value
}
init(_ value: String) {
self.init(LocalizedStringKey(value))
}
var body: some View {
if textFitsIntoAvailableSpace {
valueText
}
else {
ScrollView(.horizontal) {
valueText
}
}
}
private var valueText: some View {
return Text(value)
.detailForegroundColor()
.background(
// Render the limited text and measure its size
Text(value).lineLimit(1)
.background(GeometryReader { availableSpace in
ZStack {
// Render the text without restrictions and measure its size
Text(self.value)
.background(GeometryReader { requiredSpace in
// And compare the two
Color.clear.onAppear {
self.textFitsIntoAvailableSpace = self.textFitsIntoAvailableSpace == false ? false : availableSpace.size.width >= requiredSpace.size.width
}
})
}
.frame(width: .greatestFiniteMagnitude)
})
.hidden() // Hide the background
)
}
}
struct TextWithScrollView_Previews: PreviewProvider {
static var previews: some View {
TextWithScrollView("Text")
}
}