ios – SwiftUI LazyVGrid vs. Customized View for Selectable Tags (Glitch Impact Bug)

0
25
ios – SwiftUI LazyVGrid vs. Customized View for Selectable Tags (Glitch Impact Bug)


I’ve a selectable tag view in SwiftUI that appears just like the picture on the left. That means the gadgets are aligned to the middle and do not appear like typical SwiftUI grid (picture on the correct)

comparison of the custom view of mine - left and grid - right

It’s a customized view that appears like this:

struct FlowLayoutView: View the place Knowledge.Factor: Hashable {
let information: Knowledge
let spacing: CGFloat
let content material: (Knowledge.Factor) -> Content material

@State personal var elementsSize: [Data.Element: CGSize] = [:]

var physique: some View {
    VStack(alignment: .middle, spacing: spacing) {
        let rows = computeRows()
        ForEach(rows, id: .self) { row in
            HStack(spacing: spacing) {
                ForEach(row, id: .self) { merchandise in
                    content material(merchandise)
                        .fixedSize()
                        .readSize { measurement in
                            elementsSize[item] = measurement
                        }
                }
            }
        }
    }
}

personal func computeRows() -> [[Data.Element]] {
    var rows: [[Data.Element]] = [[]]
    var currentRowWidth: CGFloat = 0
    let screenWidth = UIScreen.essential.bounds.width - 40 // Regulate for padding

    for merchandise in information {
        let itemSize = elementsSize[item, default: CGSize(width: 100, height: 1)]

        if currentRowWidth + itemSize.width > screenWidth {
            rows.append([item])
            currentRowWidth = itemSize.width
        } else {
            rows[rows.count - 1].append(merchandise)
            currentRowWidth += itemSize.width + spacing
        }
    }

    return rows
}
}

In order one can see, the rows are computed and it would not be the issue if it weren’t for the truth that when the person selects an merchandise, the computeRows operate is triggered which ends up in a glitch or one might name a “tweak impact” (glitchy re-layout on choice).

What I would like is the environment friendly updates as they’re within the SwiftUI’s Record or LazyVGrid that permit environment friendly re-rendering as a substitute of computing rows manually each time that end in “tweak”. Then again, with Record or Grid I haven’t got the specified look (picture on the left) and have the common grid-like look (picture on the correct), however not less than I haven’t got the “tweak” impact.

Is it attainable to in some way have a Grid or the rest that would not require me to compute rows and on the similar time have the looks because the picture on the left (every thing centered; customized view I’ve now)?

LEAVE A REPLY

Please enter your comment!
Please enter your name here