onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to show anchor bottom view in SwiftUI #954

Open onmyway133 opened 1 year ago

onmyway133 commented 1 year ago

From iOS 15, there's a handy safeAreaInset that allows us to place additional content extending the safe area.

Shows the specified content beside the modified view.

safeAreaInset allows us to customize which edge and alignment we can place our views. This works for both ScrollView, List and Form and you can apply it multiple times.

The content view is anchored to the specified horizontal edge in the parent view, aligning its vertical axis to the specified alignment guide. The modified view is inset by the width of content, from edge, with its safe area increased by the same amount.

This comes very often when we want to place a fixed view either on top or bottom of the screen. In a paywall view for example, we usually show a list of IAP plan options at the bottom, to achieve that we can specify safeAreaInset(edge: .bottom) to the ScrollView. Our plansView takes a part of the safe area, and tells ScrollView to automatically adjust its inset to account for the new safe area region.

Without safeAreaInset, we have to manually calculate plansView height and adjust ScrollView content insets manually.

struct PaywallView: View {
    var body: some View {
        ScrollView {
            VStack {
                introductionView
                benefitsView
            }
        }
        .safeAreaInset(edge: .bottom) {
            plansView
                .padding()
                .frame(maxWidth: .infinity)
                .background(Material.regular)
        }
    }
}