SwiftUI和UIView

iOS开发目前主要有两种UI开发方式:

  • UIKit (UIView): 传统框架,从iOS诞生就存在
  • SwiftUI: 2019年推出的现代化声明式UI框架

此外,swiftUI还可以在苹果旗下的各类产品中,如mac,iPad,apple watch中使用。

现在新版的xcode创建默认使用swiftUI

例如

1
2
3
4
5
6
7
8
import SwiftUI

struct ContentView: View {
var body: some View {
Text("hello world")
.padding()
}
}

而UIVIew创建的App则相对较为麻烦一点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import UIKit

class HelloWorldViewController: UIViewController {

private let helloLabel: UILabel = {
let label = UILabel()
label.text = "hello world"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()

override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}

private func setupUI() {
view.backgroundColor = .white
view.addSubview(helloLabel)

NSLayoutConstraint.activate([
helloLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
helloLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
}

此外SwiftUI提供了两种方式来兼容UIKit:

  • UIViewRepresentable: 用于包装简单的UIView组件
  • UIViewControllerRepresentable: 用于包装UIViewController

这里以UIViewControllerRepresentable为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 包装UIViewController
struct UIKitViewController: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> HelloWorldViewController {
return HelloWorldViewController()
}

func updateUIViewController(_ uiViewController: HelloWorldViewController, context: Context) {
}
}

struct ContentView: View {
var body: some View {
UIKitViewController()
.padding()
}
}

两种框架的主要区别:

  • SwiftUI: 声明式语法,代码简洁,跨平台,但仅支持iOS 13+
  • UIKit: 命令式语法,代码较繁琐,成熟稳定,支持所有iOS版本

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

0%