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
            )
        }
    }
}
 
37
Kudos
 
37
Kudos

Now read this

My SwiftUI wishlist for WWDC 2020

Let me start by saying that SwiftUI is simply amazing. I’ve been working on an open-source framework called SwiftUIX for about a year now, with the ambitious goal of filling up certain gaps while we wait for Apple’s annual release cycle.... Continue →