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

Removing List’s cell separators in SwiftUI

Currently, as of Xcode 11.1, Apple provides no way for developers to specify a cell separator style for SwiftUI’s List. Having run into this issue myself, I finally stumbled upon a workaround: UITableView.appearance().separatorStyle =... Continue →