美文网首页
SwiftUI学习-(第4节)

SwiftUI学习-(第4节)

作者: BoxJing | 来源:发表于2023-06-12 17:16 被阅读0次
1.List

下图所示的List效果,在SwiftUI中,实现列表没有OC和Swift那样那么复杂,几行代码就实现了上述2种语言需要10几行甚至更多行数的效果。

List展示信息
//
//  BoxListView.swift
//  BoxSwiftUI
//
//  Created by BoxJing on 2023/6/13.
//

import SwiftUI

struct BoxListView: View {
    @State private var students = Student.examples
    var body: some View {
        VStack(alignment: .leading) {
            navBarView
            List($students, id: \.name, editActions: .all) { student in
                studentView(student.wrappedValue)
            }
            .listStyle(.plain)
            .padding(.horizontal)
        }
        .safeAreaInset(edge: .bottom,alignment: .trailing, content: {
            Image(systemName: "plus.circle.fill")
                .font(.system(size: 66))
                .padding(.trailing)
                .symbolRenderingMode(.palette)
                .foregroundStyle(.white, Color.accentColor.gradient)
        })
    }
}
extension BoxListView {
    var navBarView: some View {
        HStack {
            Label("学生列表", systemImage: "person")
                .padding()
                .foregroundColor(.accentColor)
            Spacer()
            EditButton().buttonStyle(.bordered)
                .padding(.trailing)
                .environment(\.locale, .init(identifier: "zh-Hans"))
        }
    }
    func studentView(_ student: Student) -> some View {
        HStack {
            Text(student.name)
            Spacer()
            Text(student.age.formatted())
        }
    }
}
struct BoxListView_Previews: PreviewProvider {
    static var previews: some View {
        BoxListView()
    }
}
2. AnyLayout

有时候我们会遇到2种不同的布局情况,这时候可以用AnyLayout来实现:

struct BoxDifferentLayout: View {
    @State var num:String = ""
    var body: some View {
        TextField("请输入文字", text: $num)
        Spacer()
        let shouldUseVStack = (num.count % 2 == 0)
        let layout = shouldUseVStack ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
        layout {
            Text("文字1")
            Text("文字2")
        }
    }
}

当输入的文字长度为奇数时候2个文字会横向排列,当文字长度为偶数时候2个文字会垂直排列。

3. GeometryReader

当我们需要获取位置信息时,我们在SwiftUI中可以使用GeometryReader,它包含着一个视图View的所有位置信息,会返回一个GeometryProxy实例,这使我们能够访问其容器的大小和坐标。

var body: some View {
  GeometryReader { proxy in
// proxy 里面包含所有的位置信息(x,y,width,height)
  }
}

GeometryReader仍然需要我们在它的主体中声明一个视图,我们可以使用Color.clear创建一个隐形层:

var body: some View {
  customView
    .background(
      GeometryReader { proxy in
        Color.clear
      }
    )
}
4. PreferenceKey

SwiftUI提供了PreferenceKey的功能,这是SwiftUI通过视图树传递信息的方式。
我们开始自定义一个PreferenceKey,即SizePreferenceKey:

struct SizePreferenceKey: PreferenceKey {
  static var defaultValue: CGSize = .zero
  static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

PreferenceKey是一个通用协议,需要一个静态函数和一个静态默认值:
defaultValue是被使用,当视图没有该属性的显式值时
reduce(value:nextValue:)将渲染树中找到的value值与新的value值组合在一起。
我们将使用PreferenceKey来存储我们的子元素的测量大小,回到我们的示例:

var body: some View {
  childView
    .background(
      GeometryReader { geometryProxy in
        Color.clear
          .preference(key: SizePreferenceKey.self, value: geometryProxy.size)
      }
    )
}

现在子视图的大小就在渲染树的层次结构中了!我们怎么读取呢?
SwiftUI提供了一个View的extension,onPreferenceChange(_:perform:)它让我们指定一个PreferenceKey,当该PreferenceKey发生变化时就会触发回调方法:

var body: some View {
  childView
    .background(
      GeometryReader { geometryProxy in
        Color.clear
          .preference(key: SizePreferenceKey.self, value: geometryProxy.size)
      }
    )
    .onPreferenceChange(SizePreferenceKey.self) { newSize in
      print("The new child size is: \(newSize)")
    }
}

由于onPreferenceChange,任何对此PreferenceKey感兴趣的父组件都可以提取值并在值更改时得到通知。
这种获取子视图大小的方法可以直接封装为View的扩展方便使用:

extension View {
  func getViewSize(onChange: @escaping (CGSize) -> Void) -> some View {
    background(
      GeometryReader { proxy in
        Color.clear
          .preference(key: SizePreferenceKey.self, value: proxy.size)
      }
    )
    .onPreferenceChange(SizePreferenceKey.self, perform: onChange)
  }
}

在使用的时候就方便很多:

var body: some View {
  BoxView
    .getViewSize { size in
      print("Size is: \(size)")
    }
}

相关文章

  • SwiftUI 简介

    推荐学习SwiftUI官网[https://swiftui.jokerhub.cn]学习,下面大多是官网的解释,感...

  • swiftUI 常用控件介绍

    最近在学习swiftUI,首先来介绍一下swiftUI的一些基本用法,swiftUI和Flutter的语法比较类似...

  • SwiftUI 02-构建列表和导航(Building List

    本章Demo 链接Blog 链接 简介 此示例是记录学习SwiftUI的过程,原文出自SwiftUI Essent...

  • JPDesignCode for iOS15

    SwiftUI学习项目 学自于国外一个很出名的SwiftUI课程:DesignCode[https://desig...

  • WWDC21 学习系列之 SwiftUI 支持将 Markdo

    新特性 SwiftUI 支持将 Markdown 直接传递给文本Text 示例代码 加入我们一起学习SwiftUI...

  • Swift5之开篇

    开始学习Swift5,记录一下学习的内容。 昨天开始看apple的文档,感受了下SwiftUI,SwiftUI5的...

  • SwiftUI学习

    官方基础工程简介 AppDelegate.swift 负责外部事件监听 SceneDelegate.swift 负...

  • SwiftUI学习

    学习文章 文集:Hacking with iOS: SwiftUI Edition[https://www.jia...

  • SwiftUI 中实现 K-Means 聚类,了解如何在 Swi

    想为您的 SwiftUI 应用程序添加强大的机器学习算法吗?跟着! SwiftUI 是一个用于在 Apple 平台...

  • SwiftUI控件

    SwiftUI控件 SwiftUI学习的内容还是很多的,但是我们只对我们项目实战内容所涵盖的知识点进行讲解,接下来...

网友评论

      本文标题:SwiftUI学习-(第4节)

      本文链接:https://www.haomeiwen.com/subject/ygdqydtx.html