Home > Software engineering >  I want to create a view where the hashtag is displayed in SwiftUI
I want to create a view where the hashtag is displayed in SwiftUI

Time:04-26

Currently, I am studying SwiftUI and making UI that is displayed in the view when registering hashtags. But I don't know what to do with the logic of creating and inserting a new HStack when it's out of screen size inside the VStack. I've searched several times, but I couldn't find any helpful words or keywords.

I would appreciate it if you could help me by knowing the answer.

enter image description here

The image above is an example. I want to create a new HStack and put it in the VStack when the width exceeds the horizontal size of the device while inserting a text item into the HStack.

struct HashTagView: View {
    var hashTagArray: [String] = ["#Lorem", "#Ipsum", "#dolor", "#sit", "#amet", "#consectetur", "#adipiscing", "#elit", "#Nam", "#semper", "#sit", "#amet", "#ut", "#eleifend", "#Cras"]
    
    var body: some View {
        VStack(spacing: 5)  {
            ForEach(hashTagArray, id:\.self) { tag in
                Text(tag)
            }
        }
        .padding()
        .border(Color.blue)
        .frame(width: UIScreen.main.bounds.size.width)
    }
}

this is my code.

CodePudding user response:

You should use a LazyVgrid with an adaptive layout here:

I removed some entries from your array because if you use it with id: \.self you should ensure that every entry is unique.

Documentation

struct HashTagView: View {
    var hashTagArray: [String] = ["#Lorem", "#Ipsum", "#dolor", "#consectetur", "#adipiscing", "#elit", "#Nam", "#semper", "#sit", "#amet", "#ut", "#eleifend", "#Cras"]
    
    private var gridItemLayout = [GridItem(.adaptive(minimum: 100))]
    
    var body: some View {
        ScrollView{
            LazyVGrid(columns: gridItemLayout , spacing: 5)  {
                ForEach(hashTagArray, id:\.self) { tag in
                    Text(tag)
                }
            }
            .padding()
            .border(Color.blue)
        }
        .frame(width: UIScreen.main.bounds.size.width)
    }
}
  • Related