How to read size of view?

Viewed 122

in Swift UI, I try to make a slider to control value(0…1), just like the original slider do.

I set up a rectangle with offset and width(the max offset) , and trying to link the offset with the value.

But the problem was, I use value = offset / width , and I don’t know how to get the width of rectangle. In the code below, I set width as 320frames, but I want it to be programmatic, do anyone knows how? Thanks.

import SwiftUI

struct Test: View {
    @State private var offset: CGFloat = 50
    private let width: CGFloat = 320
    
    var value: CGFloat {
        offset / width
    }

    var body: some View {
        ZStack(alignment: .leading) {
            Rectangle()
                .overlay(alignment: .leading) {
                    Rectangle()
                        .frame(width: offset)
                        .foregroundColor(.red)
                }
        }
        .frame(width: width, height: 32)
    }
}
0 Answers
Related