学会了这3个知识点,SwiftUI就真正入门了

2,705 阅读2分钟

在WWDC2019中,iOS引入了一个全新的UI框架——SwiftUI。它的目的是通过全新的设计思想来解决iPhone、iPad、Mac的界面统一,以便开发者可以通过一次学习多处使用(Learn Once, Use anywhere)。从iOS13开始我们就可以使用这个全新的框架了,iOS开发者应该尽快掌握它。

到公众号【iOS开发栈】学习更多SwiftUI、iOS开发相关内容。

View

SwiftUI中一切皆View,不论是我们熟悉的Button还是backgroundColor,甚至Color.red,它们都是View

与UIKit中的UIView不同的是,在SwiftUI中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

    /// The content and behavior of the view.
    @ViewBuilder var body: Self.Body { get }
}

SwiftUI中的View是不能直接使用的,否则会报错 {% label danger@'View' cannot be constructed because it has no accessible initializers %},当你遇到这个问题的时候请仔细思考一下你是不是真的要这么用,或许可以用一个其他的代替。

常用到的View有:Text/Button/Toggle/Picker/V(Z)(H)Stack/Color/Spacer/Image/Shape/Divider以及它们的modifier等。

@ViewBuilder标记的body变量表示它是一个容器,里面可以包含任意多个其他的View

Button(action: btnClick) {
    VStack {
        Image(systemName: "star")
        Text("Placeholder")
    }
}

Modifer

我们分别看一下在UIKit和SwiftUI中修改一个Label的文字颜色 {% tabs modify label text color %}

let label = UILabel()
label.text = "UIKit"
label.textColor = UIColor.red
Text("SwiftUI").foregroundColor(.red)

{% endtabs %}

SwiftUI中的.foregroundColortextColor有本质的不同,它是一种modifier,它返回的是令一个View。

@inlinable public func foregroundColor(_ color: Color?) -> some View

当我们调用了.foregroundColor其实是创造了一个新的View,这也正是SwiftUI中万物皆View的例子。

@State和$ —— Binding Value

struct ContentView: View {
    @State var isOn: Bool
    
    var body: some View {
        Toggle(isOn: $isOn) {
            Text("Toggle")
        }
    }
}

这是一个双向绑定

绑定建立以后,不论是isOn的修改触发了Toggle状态的改变,还是用户点击了Toggle引起isOn变量值的改变我们都不需要关心,SwiftUI会帮我们完成。

到公众号【iOS开发栈】学习更多SwiftUI、iOS开发相关内容。

本文首发在我的个人技术博客