Skip to content

Instantly share code, notes, and snippets.

@TomQDRS
Created August 6, 2021 14:30
Show Gist options
  • Save TomQDRS/850ed6da139d146e0c6732f84b138923 to your computer and use it in GitHub Desktop.
Save TomQDRS/850ed6da139d146e0c6732f84b138923 to your computer and use it in GitHub Desktop.
Wraps a SwiftUI Text View in a VStack and offers a Button that toggles an expanded state by changing the maximum number of lines.
//
// ExpandableText.swift
//
// Created by TomQDRS on 06.08.21.
//
import SwiftUI
extension Text {
func expandable() -> some View {
return self.modifier(ExpandableText())
}
}
struct ExpandableText: ViewModifier {
@State private var isExpanded: Bool = false
private var chevron: Image {
isExpanded ? Image(systemName: "chevron.up") : Image(systemName: "chevron.down")
}
func body(content: Content) -> some View {
VStack(alignment: .leading, spacing: 8) {
content.lineLimit(isExpanded ? nil : 2)
Button {
withAnimation {
isExpanded.toggle()
}
} label: {
HStack(spacing: 4) {
Text(isExpanded ? "show less" : "show more")
chevron
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment