From e1dc85b3e876c74820777f2aeeb128408687a84c Mon Sep 17 00:00:00 2001 From: Jerrad Thramer Date: Tue, 31 Oct 2023 16:54:20 -0600 Subject: [PATCH] Adding ability and switch for `ExpandableView` to be collapsed by tapping on expanded text body. --- Example/ExpandableTextExample/ContentView.swift | 1 + Sources/ExpandableText/ExpandableText+Modifiers.swift | 11 +++++++++++ Sources/ExpandableText/ExpandableText.swift | 4 +++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Example/ExpandableTextExample/ContentView.swift b/Example/ExpandableTextExample/ContentView.swift index 3ac48f1..8590a9b 100644 --- a/Example/ExpandableTextExample/ContentView.swift +++ b/Example/ExpandableTextExample/ContentView.swift @@ -31,6 +31,7 @@ struct ContentView: View { .moreButtonColor(.red) .expandAnimation(.easeInOut(duration: 2)) .trimMultipleNewlinesWhenTruncated(false) + .enableCollapse(true) .border(.red) ExpandableText("**Markdown** is _supported_") diff --git a/Sources/ExpandableText/ExpandableText+Modifiers.swift b/Sources/ExpandableText/ExpandableText+Modifiers.swift index 7b095b5..d7cb4ee 100644 --- a/Sources/ExpandableText/ExpandableText+Modifiers.swift +++ b/Sources/ExpandableText/ExpandableText+Modifiers.swift @@ -87,6 +87,17 @@ public extension ExpandableText { return copy } + /** + Enables collapsing behavior by tapping on the text body when the state is expanded. + - Parameter value: Whether or not to enable collapse functionality. + - Returns: A new `ExpandableText` instance with the specified collapse ability applied. + */ + func enableCollapse(_ value: Bool) -> Self { + var copy = self + copy.collapseEnabled = value + return copy + } + /** Sets whether multiple consecutive newline characters should be trimmed when truncating the text in the `ExpandableText` instance. - Parameter value: A boolean value indicating whether to trim multiple consecutive newline characters. Defaults to `true` diff --git a/Sources/ExpandableText/ExpandableText.swift b/Sources/ExpandableText/ExpandableText.swift index a70df8e..43cdff0 100644 --- a/Sources/ExpandableText/ExpandableText.swift +++ b/Sources/ExpandableText/ExpandableText.swift @@ -42,6 +42,7 @@ public struct ExpandableText: View { internal var moreButtonFont: Font? internal var moreButtonColor: Color = .accentColor internal var expandAnimation: Animation = .default + internal var collapseEnabled: Bool = false internal var trimMultipleNewlinesWhenTruncated: Bool = true /** @@ -79,7 +80,8 @@ public struct ExpandableText: View { ) .contentShape(Rectangle()) .onTapGesture { - if shouldShowMoreButton { + if (isExpanded && collapseEnabled) || + shouldShowMoreButton { withAnimation(expandAnimation) { isExpanded.toggle() } } }