SwiftUI实战-仿写微信App(五)

1,484 阅读2分钟

这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战

前文

一、目标

image.png

发现的布局都是简单的List布局,所以今天一次性写完。

二、List + NavigationLink联动

SwiftUI中,一旦组合使用二者,List会默认将给子元素增加一个>图标,寓意可以点击查看。

使用Section可以将子元素,分成一个个小块。

image.png

List组件指定.listStyle(GroupedListStyle())属性,可以实现微信的列表效果。

image.png

除此之外,listStyle还支持以下几种样式:

  • DefaultListStyle
  • GroupedListStyle
  • InsetGroupedListStyle
  • InsetListStyle
  • PlainListStyle
  • SidebarListStyle

image.png

回归正题,稍加改动,很容易实现以下效果:

image.png

再加上跳转

 NavigationLink(
    destination: Text("Destination"),
    label: {
        HStack{
            Image(systemName: "text.justifyright").foregroundColor(.blue)
            Text("朋友圈").foregroundColor(.black)
        }
    })

屏幕录制2021-08-05 20.58.39.gif

后续的一些功能和后面的页,大部分都可以用之前讲过的知识点来实现,这里不再做具体实现。

我会将没有描述过的,微信里的一些功能或组件拉出来做实现。

三、sheet

图层.tiff

这种浮出一半遮罩层SwiftUI是没办法原生支持的,SwiftUI提供了一种弹窗遮罩层,如下图:

屏幕录制2021-08-05 21.24.49.gif

struct ModalView: View {
    
    @State var sheetIsPresented = false
    
    var body: some View {
        Button(action: {
            sheetIsPresented = true
        }, label: {
            Text("打开遮罩层")
        }).sheet(isPresented: $sheetIsPresented, content: {
            ZStack{
                Rectangle().fill().foregroundColor(.blue)
                Button(action: {
                    sheetIsPresented = false
                }, label: {
                    Text("返回").foregroundColor(.white)
                })
            }
           
        })
    }
}
  • Button按钮增加一个.sheet属性。
  • isPresented参数用来控制遮罩层的显示与否。
  • content包裹的就是遮罩层的内容。

四、actionSheet

image.png

SwiftUI提供这种底部弹出按钮的方式,actionSheet

屏幕录制2021-08-05 22.01.06.gif

struct ActionSheetView: View {
    
    @State var actionSheetIsPresented = false
    
    var body: some View {
        Button(action: {
            actionSheetIsPresented = true
        }, label: {
            Text("打开actionSheet")
        }).actionSheet(isPresented: $actionSheetIsPresented, content: {
            ActionSheet(title: Text("Print Color"), message: Text("Select a new color"), buttons: [
                    .default(Text("Black")) { print("Red") },
                    .default(Text("Green")) { print("Green") },
                    .default(Text("Blue")) { print("Blue") },
                .destructive(Text("Red")),
                    .cancel(Text("取消"))
                ])
        })
    }
}

  • Button按钮增加一个.actionSheet属性。
  • isPresented参数用来控制actionSheet的显示与否。
  • sheet不同的是,content内必须是ActionSheet组件。
  • buttons:.default是普通选项;.cancel是取消选项;.destructive是红色字体选项。
  • cancel默认是英文cancel,如果要改成自定义的文本,内容使用Text即可。

附:代码地址

gitee.com/dkwingcn/we…