美文网首页
SwiftUI显示更多文字与收起文字

SwiftUI显示更多文字与收起文字

作者: 纵横四海 | 来源:发表于2021-10-11 15:06 被阅读0次
    import SwiftUI
    struct LongText: View {
    
        /* Indicates whether the user want to see all the text or not. */
        @State private var expanded: Bool = false
    
        /* Indicates whether the text has been truncated in its display. */
        @State private var truncated: Bool = false
    
        private var text: String
    
        var lineLimit = 3
    
        init(_ text: String) {
            self.text = text
        }
    
        var body: some View {
            VStack(alignment: .leading) {
                // Render the real text (which might or might not be limited)
                Text(text)
                    .lineLimit(expanded ? nil : lineLimit)
    
                    .background(
    
                        // Render the limited text and measure its size
                        Text(text).lineLimit(lineLimit)
                            .background(GeometryReader { displayedGeometry in
    
                                // Create a ZStack with unbounded height to allow the inner Text as much
                                // height as it likes, but no extra width.
                                ZStack {
    
                                    // Render the text without restrictions and measure its size
                                    Text(self.text)
                                        .background(GeometryReader { fullGeometry in
    
                                            // And compare the two
                                            Color.clear.onAppear {
                                                self.truncated = fullGeometry.size.height > displayedGeometry.size.height
                                            }
                                        })
                                }
                                .frame(height: .greatestFiniteMagnitude)
                            })
                            .hidden() // Hide the background
                )
    
                if truncated && !expanded { toggleButton }
            }
        }
    
        var toggleButton: some View {
            Button(action: { self.expanded.toggle() }) {
                Text(self.expanded ? "Show less" : "Show more")
                    .font(.caption)
                
            }
        }
    }
    
    struct LongText_Previews: PreviewProvider {
        static var previews: some View {
            /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
        }
    }
    
    

    使用方法

      LongText("This is very long text designed to create enough wrapping to force a More button to appear. Just a little more should push it over the edge and get us to one more line.")
    

    相关文章

      网友评论

          本文标题:SwiftUI显示更多文字与收起文字

          本文链接:https://www.haomeiwen.com/subject/huomwltx.html