Search code examples
iosswiftuilabeltruncate

Swift UILabel place button after truncate tail with limited lines


I'm new in Swift and I'm currently working on a project. An example I want to emulate is youtube, where when a comment is too long a 'Read more' button(?) appears after the truncate tail. I want to have the same kind of button for a truncated comment but I failed to find a way to do it.

The closest answer I found was at this link but I'm currently working on the storyboard and code so it was hard for me to understand. Decrease the width of the last line in multiline UILabel

Youtube comment capture

If anyone had done this before or knows how to do this it would be helpful to share your tips.


Solution

  • struct ContentView: View {
        @State var showDetail = false
        var body: some View {
            HStack(alignment:.lastTextBaseline,spacing:-1){
                Text("There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.dadasdsadsadsadsadsadsadsadsadasdsad")
                Button(action: {
                    self.showDetail.toggle()
                }, label: {
                    HStack(spacing:0){
                        
                        Text("More")
                            .font(.caption)
                            .foregroundColor(.black)
                        Image(systemName: "chevron.down")
                        
                    }.font(.caption)
                    .foregroundColor(.black)
                })
            }.frame(width: 300, height: self.showDetail == true ? 500 : 300)
            .animation(.spring())
    
        }
    }