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

@ -37,8 +37,11 @@ struct LabelledUIKitTextField: View {
var textChanged: ((String) -> Void)? = nil
@State private var textFitsIntoAvailableSpace: Bool = true
var body: some View {
HStack {
HStack(alignment: .center) {
Text(label)
.onTapGesture {
DispatchQueue.main.async {
@ -48,15 +51,40 @@ struct LabelledUIKitTextField: View {
Spacer()
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)
if textFitsIntoAvailableSpace {
textField
}
else {
ScrollView(.horizontal) {
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)
})
.hidden() // Hide the background
)
)
if isTruncated {
Button(action: { self.isExpanded.toggle() }) {