为Swift UI视图创建自定义修饰符

时间:2019-07-08 22:00:12

标签: ios swift swiftui

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

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

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
   }
}

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

LabelView()
  .font1(.callout)
  .font2(.body)

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

2 个答案:

答案 0 :(得分:2)

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

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

extension LabelView {
    func font1(_ font1: Font) -> Self {
        var copy = self
        copy.font1 = font1
        return copy
    }
}

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

extension View {
    func modifying<T>(_ keyPath: WritableKeyPath<Self, T>, value: T) -> Self {
        var copy = self
        copy[keyPath: keyPath] = value
        return copy
    }
}

两种版本的用法:

struct LabelView: View {
    var font1: Font = .headline
    var font2: Font = .body
    var body: some View { ... }
}

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

结果如下:

Resulting view

答案 1 :(得分:1)

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

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.")
    }
}