关于ios:为Swift UI视图创建自定义修饰符

Creating custom modifiers for Swift UI views

想知道如何为Swift UI视图创建修饰符吗?

例如,假设我有一些这样定义的视图:

1
2
3
4
5
6
7
8
struct LabelView: View {
   let font1: Font = .header
   let font2: Font = .body

   var body: Some View {
     // two views, where one uses font1 and other uses font2
   }
}

如何创建允许类似以下内容的修饰符:

1
2
3
LabelView()
  .font1(.callout)
  .font2(.body)

我正在尝试学习如何编写声明性的API(Apple正在使用Swift UI进行推送),但似乎文档还不完善。我已经尝试创建某种ViewModifier类型,但是我不太确定该怎么做,因为它需要我返回_ModifiedContent<_, _>且不确定如何执行。基本上,可以使用声明性语法来修改视图的属性,例如内置的SwiftUI视图中的语法。


如dfd中的注释所链接,您可以使用Apple提供的修饰符创建自定义修饰符。您也可以创建自己的方法来修改var

注意:您不能在这里使用变异方法,因为函数构建器会返回不可变的值。您会收到一个编译器错误。您需要复制self并将其返回。

1
2
3
4
5
6
7
extension LabelView {
    func font1(_ font1: Font) -> Self {
        var copy = self
        copy.font1 = font1
        return copy
    }
}

您还可以创建使用密钥路径更新变量的通用版本:

1
2
3
4
5
6
7
extension View {
    func modifying< T >(_ keyPath: WritableKeyPath<Self, T>, value: T) -> Self {
        var copy = self
        copy[keyPath: keyPath] = value
        return copy
    }
}

两个版本的用法:

1
2
3
4
5
6
7
8
9
struct LabelView: View {
    var font1: Font = .headline
    var font2: Font = .body
    var body: some View { ... }
}

LabelView()
    .modifying(\\.font2, value: .callout)
    .font1(.largeTitle)

结果如下:

Resulting


看看这是否是您想要的东西。您可以根据需要简单地修改属性。如果需要固定的textView,则将其保持在自定义labelView中为静态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import SwiftUI

struct LabelView: View {
    var font1: Font = .headline
    var font2: Font = .subheadline
    var text1: String =""
    var text2: String =""
    var body: some View {
        VStack {
            Text(text1).lineLimit(nil).font(font1)
            Text(text2).lineLimit(nil).font(font2)
        }
    }
}

struct StackOverFlow : View {
    var body: some View {
        //LabelView(font1: .title, font2: .subheadline )
        LabelView(font1: .title, font2: .subheadline, text1:"What is Lorem Ipsum?", text2:"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.")
    }
}