SwiftUI 自定义一个以 View 作为参数的 ViewModifier
创始人
2024-06-02 18:22:54

SwiftUI 自定义一个以 View 作为参数的 ViewModifier

假设我们有以下需求:

自定义一个 sheet ,当 iOS 版本为 16.0 以上时,可以指定弹出 sheet 的高度,而当 iOS 版本为 16.0 以下时,弹出的 sheet 为默认高度。

sheet 的官方声明如下

func sheet(isPresented: Binding, onDismiss: (() -> Void)? = nil, @ViewBuilder content: @escaping () -> Content) -> some View where Content : View

因此我们必须向它传递 isPresentedcontent 两个参数,再加上我们指定的高度,总共需要传递三个参数给我们的 modifier,代码如下:

import SwiftUIstruct customSheetModifier: ViewModifier {@Binding var isPresented: Boolvar fraction: CGFloat = 0.5var sheetContent: () -> SheetContentfunc body(content: Content) -> some View {Group {if #available(iOS 16.0, *) {content.sheet(isPresented: $isPresented) {sheetContent().presentationDetents([.fraction(fraction)])}} else {content.sheet(isPresented: $isPresented) {sheetContent()}}}}
}

这里我们使用了 Swift 的泛型来实现。

为了使用更便利,我们可以创建以下的 extension 来使用我们的 modifier:

extension View {func customSheet(isPresented: Binding, fraction: CGFloat = 0.5, sheetContent: @escaping () -> SheetContent) -> some View where SheetContent: View {modifier(customSheetModifier(isPresented: isPresented,fraction: fraction, sheetContent: sheetContent))}
}
💡 函数中形参的声明中 @escaping 代表逃逸闭包,一般当闭包的生命周期超过当前函数生命周期时使用

这样,我们只需要在 View 中使用 .customSheet 即可调用自定义的 sheet 了。

使用方法如下:

在需要使用自定义 sheet 的 View 中,使用 .customSheet modifier 即可。例如:

@State var sheetPresented = falsevar body: some View {Button("Show Sheet") {sheetPresented.toggle()}.customSheet(isPresented: $sheetPresented, fraction: 0.7) {SheetView()}
}

其中,SheetView() 为自定义的 sheet 内容,fraction 参数为我们指定的高度占屏幕的比例。

相关内容

热门资讯

原创 恋... 2026年刚刚开始,娱乐圈的吃瓜新闻便接连不断。先是司晓迪爆料某男明星的私事,紧接着是刘一诺与檀健次...
为何近期污染范围较大?成都市生... 1月12日,红星新闻记者了解到,根据省级生态环境和气象部门空气质量前期联合会商结果,1月8日起,四川...
最新或2023(历届)四川美术... 最新或2023(历届)四川美术联考/统考色彩考试题目  考题:食堂今日菜品  一、必备内容:  以食...
最新或2023(历届)四川美术... 明日素描、速写考试  素描 最新或2023(历届)12月6日上午09:00-12:00(满分100分...
最新或2023(历届)福建高考... 福建最新或2023(历届)高考招生艺体类统考12月中旬开考 福建省最新或2023(历届)高招艺术类、...