Implemented wrapping UIKitTextField in a scroll view if text doesn't fit into available space

This commit is contained in:
dankito 2020-09-14 22:47:19 +02:00
parent 50c6a72dff
commit c38f6a6e1a
2 changed files with 36 additions and 8 deletions

View File

@ -36,9 +36,12 @@ struct LabelledUIKitTextField: View {
var textChanged: ((String) -> Void)? = nil var textChanged: ((String) -> Void)? = nil
@State private var textFitsIntoAvailableSpace: Bool = true
var body: some View { var body: some View {
HStack { HStack(alignment: .center) {
Text(label) Text(label)
.onTapGesture { .onTapGesture {
DispatchQueue.main.async { DispatchQueue.main.async {
@ -48,14 +51,39 @@ struct LabelledUIKitTextField: View {
Spacer() Spacer()
UIKitTextField(placeholder, text: $text, if textFitsIntoAvailableSpace {
keyboardType: keyboardType, autocapitalizationType: autocapitalizationType, addDoneButton: addDoneButton, textField
isPasswordField: isPasswordField, }
focusOnStart: focusOnStart, focusNextTextFieldOnReturnKeyPress: focusNextTextFieldOnReturnKeyPress, focusTextField: focusTextFieldBinding, else {
isFocusedChanged: isFocusedChanged, textAlignment: .right, isUserInputEnabled: isUserInputEnabled, ScrollView(.horizontal) {
actionOnReturnKeyPress: actionOnReturnKeyPress, textChanged: textChanged) textField
}
}
} }
} }
private var textField: some View {
UIKitTextField(placeholder, text: $text,
keyboardType: keyboardType, autocapitalizationType: autocapitalizationType, addDoneButton: addDoneButton,
isPasswordField: isPasswordField,
focusOnStart: focusOnStart, focusNextTextFieldOnReturnKeyPress: focusNextTextFieldOnReturnKeyPress, focusTextField: focusTextFieldBinding,
isFocusedChanged: isFocusedChanged, textAlignment: .right, isUserInputEnabled: isUserInputEnabled,
actionOnReturnKeyPress: actionOnReturnKeyPress, textChanged: textChanged)
.background(
// Render the limited text and measure its size
Text(text).lineLimit(1)
.background(GeometryReader { availableSpace in
Color.clear.onAppear {
let textsFrame = availableSpace.frame(in: .global)
self.textFitsIntoAvailableSpace = textsFrame.maxX <= UIScreen.main.bounds.width
}
})
.hidden() // Hide the background
)
}
} }

View File

@ -54,7 +54,7 @@ struct CollapsibleText: View {
.frame(height: .greatestFiniteMagnitude) .frame(height: .greatestFiniteMagnitude)
}) })
.hidden() // Hide the background .hidden() // Hide the background
) )
if isTruncated { if isTruncated {
Button(action: { self.isExpanded.toggle() }) { Button(action: { self.isExpanded.toggle() }) {