Is there any way to access the stroke width (or style) within a SwiftUI view?

118 Views Asked by At

I want to create a custom Shape and give it the same height as its stroke width.

struct HorizontalLine: Shape {
        
    func path(in rect: CGRect) -> Path {
        let verticalCenter = rect.height / 2
        var path = Path()
        path.move(to: .init(x: 0, y: verticalCenter))
        path.addLine(to: .init(x: rect.width, y: verticalCenter))
        return path
    }
    
    func sizeThatFits(_ proposal: ProposedViewSize) -> CGSize {
        .init(width: proposal.width, height: lineWidth)
    }                                //      ↑ ↑ ↑ ↑ ↑
                                     //  How to obtain this?
}

I know that I can wrap that whole view in a .frame(height: ...) modifier, but that's not what I want as it would create a redundancy (specify the height in both the stroke width and the height of the container view).

I want the HorizontalLine view to be "smart", so that it self-sizes according to the line width as specified in an outer stroke(lineWidth:) modifier.

Is there any way to access the lineWidth from within this shape?

It doesn't seems to be provided by the @Environment.

0

There are 0 best solutions below