SwiftUI - Data Binding注解

小知识,大挑战!本文正在参与「程序员必备小知识」创作活动 本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金

在UIKit时代,我们是如何管理model呢?依赖于UIViewController,它作为数据源和视图的粘合剂,成为数据和视图沟通的桥梁。而SwiftUI改变了这一模式,使用数据(state)来驱动UI和行为。

SwiftUI的核心思想

  1. Data access = dependency
  2. Single source of truth

怎么理解呢?我们先来看一下View的定义

public protocol View {

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required `body` property.
    associatedtype Body : View

    /// Declares the content and behavior of this view.
    var body: Self.Body { get }
}
复制代码

这个protocol唯一需要是body,我们可以把一个View看作一个function,它的返回值就是一个视图。可以决定视图内容的数据来自于function的参数,以及自身的一些局部变量。

了解过react的小伙伴们一定能感受到,入参就相当于外部传入的props,而局部变量就是state、useState
复制代码

在SwiftUI中最直观的体现便是@State,@Binding。

@State

官方建议将@State 修饰的值设置为private,它应仅属于当前视图。我们发现我们通常写的View也是一个struct(这并不是说我们不能使用class,若要使用class,要将这个class标识为final),也就是说创建出的view也是值类型。用@State标识的值,便将该值控制权交给了SwiftUI,对这个属性进行赋值的操作将会触发 View 的刷新,它的 body会被再次调用,底层渲染引擎会找出界面上与这个值相关的改变部分,并进行刷新。

但这样的类型不适合在对象间进行传递。还记得我们在之前的demo中将一个颜色值传递给了SlideView,如果此处用的是单纯的值类型,那么在传参是进行了值拷贝,在SlideView中对值的修改将无法作用于外部的视图了。

@Binding

@Binding 就是用来解决这个问题的。和@State类似,@Binding也是对属性的修饰,它做的事情是将值语义的属性“转换”为引用语义。对被声明为@Binding的属性进行赋值,改变的将不是属性本身,而是它的引用,这个改变将被向外传递。为什么要在这个变量名前添加一个$呢?

在一个@符号修饰的变量前加上$所取得的值,我们称之为投影属性 (projection property)。有些@属性,比如这里的@State和@Binding,提供这种投影属性的获取方式,它们的投影属性就是自身所对应的Binding类型。在此后便是将State转换成了引用语义。并不是所有以@修饰的变量都可以做这样的转换,比如@ObservedObject,@EnvironmentObject。

@State 进一步理解

通常我们会把什么样类型的属性声明为@State呢?基础类型,比如StringBool等,那么它是否可以是有复杂一点的类型呢?比如自定义的struct或class,我们来写个简单的例子验证一下:

struct Profile {
    var isRegistered: Bool = false
    var name: String = ""
    
    mutating func register() {
        self.name = "Ray"
        self.isRegistered = true
    }
}

struct StarterView: View {
    @State var profile: Profile
    var body: some View {
        VStack {
            Text("Hi (profile.name)")
            Button(action: {
                self.profile.register()
            }) {
                Text("Register")
            }
        }
    }
}
复制代码

页面上有一个button,点一下会发现没有问题,得到我们希望的结果,此时如果我们把Profile由struct变为class呢,会发现,点击button后,页面没有任何变化,所以@State只应该用于标注值类型。那么此时如果register是一个异步操作,比如:

struct Profile {
    var isRegistered: Bool = false
    var name: String = ""
    
    mutating func register() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            self.name = "Ray"
        }
    }
}
复制代码

我们会发现编译器报错,struct不支持此操作,这时的解决方案便是@ObservedObject。

@ObservedObject

在这里,我们举一个简单的例子,计时器,它的时钟要同步在这个View上。完整代码请移步github

struct ContentView: View {
  ...
  @ObservedObject var counter: TimeCounter
  ...
  var body: some View {
    VStack {
      HStack {
        ...
        MatchingView(rGuess: $rGuess, gGuess: $gGuess, bGuess: $bGuess, counter: $counter.counter)
      }
      ...
    }
  }
}
复制代码

@ObservedObject标示了一个来自于外部的state,而TimeCounter的代码如下所示:

class TimeCounter: ObservableObject {
  var timer: Timer?
  @Published var counter = 0

  init() {
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
      self.counter += 1
    }
  }
    
  func killTimer() {
    timer?.invalidate()
      timer = nil
    }
}
复制代码

TimeCounter需要实现ObservableObject协议。在其内部定义的的counter标示为@Published后,使用方就可以像内部的@State一样使用它。这样的模式让我们不经想到了MVVM。
这个TimeCounter也可以被多个View共享,成为多个View的数据源。

@EnvironmentObject

有了上一个多个View共享一个state的概念,那么EnvironmentObject就比较好理解了,EnvironmentObject就是整个App共享的的一个state,app里的所有View都可以获取到里面的信息。
首先,我们定义一个需要被全局共享的model:

class UserSettings: ObservableObject {
  @Published var score = 0
}
复制代码

其次,在初始化根视图时,将这个全局共享的model实例化,并进行注入。

var settings = UserSettings() 
window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(settings))
复制代码

最后,我们就可以在任何一个View中通过@EnvironmentObject var settings的方式进行引用。

struct ContentView: View {
  @EnvironmentObject var settings: UserSettings
  var body: some View {
    VStack {
      Button(action: { self.settings.score += 1 }) {
        Text("Current Score: (self.settings.score)")
      }
    }
  }
}
复制代码

这种Global的环境变量可以设置多个,直接链式调用即可UIHostingController(rootView: ContentView().environmentObject(settings).environmentObject(profile))
系统还为我们提供了很多一些环境变量

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension EnvironmentValues {

    /// The default font of this environment.
    public var font: Font?

    /// The display scale of this environment.
    public var displayScale: CGFloat

    /// The image scale for this environment.
    @available(OSX, unavailable)
    public var imageScale: Image.Scale

    /// The size of a pixel on the screen. Equal to 1 / displayScale.
    public var pixelLength: CGFloat { get }

    /// The accessibility bold text setting.
    public var legibilityWeight: LegibilityWeight?

    /// The current locale that views should use.
    public var locale: Locale

    /// The current calendar that views should use when handling dates.
    public var calendar: Calendar

    /// The current time zone that views should use when handling dates.
    public var timeZone: TimeZone

    /// The color scheme of this environment.
    ///
    /// If you're writing custom drawing code that depends on the current color
    /// scheme, you should also consider the `colorSchemeContrast` property.
    /// You can specify images and colors in asset catalogs
    /// according to either the `light` or `dark` color scheme, as well as
    /// standard or increased contrast. The correct image or color displays
    /// automatically for the current environment.
    ///
    /// You only need to check `colorScheme` and `colorSchemeContrast` for
    /// custom drawing if the differences go beyond images and colors.
    public var colorScheme: ColorScheme

    /// The contrast associated with the color scheme of this environment.
    public var colorSchemeContrast: ColorSchemeContrast { get }
}
复制代码

使用起来只需要

struct StarterView {
    @EnvironmentObject var profile: Profile
    @Environment(.locale) var locale: Locale
    ...
}
复制代码

SwiftUI给我们提供了一套依赖注入框架哟,使用得当将威力无穷。

猜你喜欢

转载自juejin.im/post/7016589971821690888