damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

TruncatedText.swift (1690B)


      1 //
      2 //  TruncatedText.swift
      3 //  damus
      4 //
      5 //  Created by William Casarin on 2023-04-06.
      6 //
      7 
      8 import SwiftUI
      9 
     10 struct TruncatedText: View {
     11     let text: CompatibleText
     12     let maxChars: Int
     13     let show_show_more_button: Bool
     14     
     15     init(text: CompatibleText, maxChars: Int = 280, show_show_more_button: Bool) {
     16         self.text = text
     17         self.maxChars = maxChars
     18         self.show_show_more_button = show_show_more_button
     19     }
     20     
     21     var body: some View {
     22         let truncatedAttributedString: AttributedString? = text.attributed.truncateOrNil(maxLength: maxChars)
     23         
     24         if let truncatedAttributedString {
     25             Text(truncatedAttributedString)
     26                 .fixedSize(horizontal: false, vertical: true)
     27         } else {
     28             text.text
     29                 .fixedSize(horizontal: false, vertical: true)
     30         }
     31         
     32         if truncatedAttributedString != nil {
     33             Spacer()
     34             if self.show_show_more_button {
     35                 Button(NSLocalizedString("Show more", comment: "Button to show entire note.")) { }
     36                     .allowsHitTesting(false)
     37             }
     38         }
     39     }
     40 }
     41 
     42 struct TruncatedText_Previews: PreviewProvider {
     43     static var previews: some View {
     44         VStack(spacing: 100) {
     45             TruncatedText(text: CompatibleText(stringLiteral: "hello\nthere\none\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven"), show_show_more_button: true)
     46                 .frame(width: 200, height: 200)
     47             
     48             TruncatedText(text: CompatibleText(stringLiteral: "hello\nthere\none\ntwo\nthree\nfour"), show_show_more_button: true)
     49                 .frame(width: 200, height: 200)
     50         }
     51     }
     52 }