美文网首页
SwiftUI基础

SwiftUI基础

作者: 小凡凡520 | 来源:发表于2019-10-16 15:40 被阅读0次
一、说明

SwiftUI是2019年WWDC新推出的UI相关的API

SwiftUI允许您忽略Interface Builder(IB)和storyboards,而无需编写详细的逐步说明来布置UI。

SwiftUI可以与其代码并排预览SwiftUI视图 - 对一侧的更改将更新另一侧,因此它们始终保持同步。

SwiftUI不会取代UIKit - 比如Swift和Objective-C,你可以在同一个应用程序中使用它们。

二、环境准备

Xcode 11 ,Mac OS 10.15及以上系统,iOS 13以及以上系统

三、预览SwiftUI视图

代码旁边有一个很大的空白区域,位于顶部:


3691932-4f9a93675923900b.png

单击Resume,稍等片刻以查看预览:


3691932-1fa9fe44efabdb50.png

如果没有看到Resume按钮,请单击editor options按钮,然后选择Editor and Canvas:


3691932-71774c8db68a022d.png

如果您仍然没有看到Resume按钮,请确保您正在运行macOS 10.15以及以上系统

四、声明式编程

使用各自的DSL来描述“UI应该是什么样子”

struct ContentView: View {
    
    var body: some View {
        Text("Hello World")
    }
}
五、SwiftUI控件
18569867-c01ceac0e21aa28b.png
六、APP 的启动

iOS 13 中新加入的通过 Scene 管理 app 生命周期的方式,以及多窗口支持部分所需要的代码。在 app 完成启动后,控制权被交接给 SceneDelegate


3637572-ec49b73e2ca76776.png
七、some View

View是SwiftUI的最核心的一个协议,代表了一个屏幕上元素的描述。这个协议中含有一个 associatedtype:

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

如果我们指明 Body 的类型,也是可以的,例如:

struct VV: View {
    var body: some View {
        Text("世界和平")
            .foregroundColor(Color.red)
    }
}
八、布局

在SwiftUI里上面Text的声明只是纯数据结构的描述,并不是实际显示出来的视图,SwiftUI 会直接读取 DSL 内部描述信息并收集起来,然后转换成基本的图形单元,最终交给底层 Metal 或 OpenGL 渲染出来。

九、Modifier
VStack(alignment: .leading) {
    Text("世界和平")
        .font(.title)
}
十、数据绑定

SwiftUI中一个很便捷的功能是视图与数据的绑定,而且绑定数据的方式非常的优雅,在初始化方法中通过 $ 声明某个属性便可以让视图自动绑定此变量

struct VV: View {
    @State var showFavoritesOnly = true
    var body: some View {

        Toggle(isOn: $showFavoritesOnly){
            Text("test")
        }
    }
}
十一、ForEach

待续。。。。。。。

十二、demo
import SwiftUI

struct ContentView: View {
    let heros:[Hero] = [
        Hero(name: "Test1"),
        Hero(name: "Test2"),
        Hero(name: "Test3"),
        Hero(name: "Test1"),
        Hero(name: "Test2"),
        Hero(name: "Test3"),
        Hero(name: "Test1"),
        Hero(name: "Test2"),
    ]
    var body: some View {
        List(heros) {
            hero in
            Text("\(hero.name)")
        }
    }
}

struct Hero:Identifiable {
    let id:UUID = UUID()
    let name: String
}

struct ContentView_Preview: PreviewProvider {
    
    static var previews: some View {
        ContentView()
    }
}

相关文章

网友评论

      本文标题:SwiftUI基础

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