Reimplementing SwiftUI’s deprecated relative view sizing functions.

With Xcode 11 beta 4, Apple deprecated SwiftUI’s View.relativeSize function (as well as View.relativeWidth and View.relativeHeight).

The relativeWidth(_:), relativeHeight(_:), and relativeSize(width:height:) modifiers are deprecated. Use other modifiers like frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:) instead. (51494692)

For those dismayed by these changes, there’s an easy reimplementation available using GeometryReader:

extension View {
    public func relativeHeight(
        _ ratio: CGFloat,
        alignment: Alignment = .center
    ) -> some View {
        GeometryReader { geometry in
            self.frame(
                height: geometry.size.height * ratio,
                alignment: alignment
            )
        }
    }

    public func relativeWidth(
        _ ratio: CGFloat,
        alignment: Alignment = .center
    ) -> some View {
        GeometryReader { geometry in
            self.frame(
                width: geometry.size.width * ratio,
                alignment: alignment
            )
        }
    }

    public func relativeSize(
        width widthRatio: CGFloat,
        height heightRatio: CGFloat,
        alignment: Alignment = .center
    ) -> some View {
        GeometryReader { geometry in
            self.frame(
                width: geometry.size.width * widthRatio,
                height: geometry.size.height * heightRatio,
                alignment: alignment
            )
        }
    }
}
 
4
Kudos
 
4
Kudos

Now read this

Songs of the Week #3

I’ve been putting off writing in favor of professional crastination, but no more! This is technically week 5 or 6, but “mah blog mah rulez” - I’m going to call it week 3. Boasty (feat. Idris Elba) by Wiley, Stefflon Don & Sean Paul #... Continue →