damus

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

TruncatedText.swift (1442B)


      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     
     14     init(text: CompatibleText, maxChars: Int = 280) {
     15         self.text = text
     16         self.maxChars = maxChars
     17     }
     18     
     19     var body: some View {
     20         let truncatedAttributedString: AttributedString? = text.attributed.truncateOrNil(maxLength: maxChars)
     21         
     22         if let truncatedAttributedString {
     23             Text(truncatedAttributedString)
     24                 .fixedSize(horizontal: false, vertical: true)
     25         } else {
     26             text.text
     27                 .fixedSize(horizontal: false, vertical: true)
     28         }
     29         
     30         if truncatedAttributedString != nil {
     31             Spacer()
     32             Button(NSLocalizedString("Show more", comment: "Button to show entire note.")) { }
     33                 .allowsHitTesting(false)
     34         }
     35     }
     36 }
     37 
     38 struct TruncatedText_Previews: PreviewProvider {
     39     static var previews: some View {
     40         VStack(spacing: 100) {
     41             TruncatedText(text: CompatibleText(stringLiteral: "hello\nthere\none\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven"))
     42                 .frame(width: 200, height: 200)
     43             
     44             TruncatedText(text: CompatibleText(stringLiteral: "hello\nthere\none\ntwo\nthree\nfour"))
     45                 .frame(width: 200, height: 200)
     46         }
     47     }
     48 }