31 Star 240 Fork 60

编程语言算法集 / SwiftUI

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README_CN.md 19.32 KB
一键复制 编辑 原始数据 按行查看 历史
Tofu 提交于 2022-02-12 17:17 . Update README_CN.md

Build Status Swift Xcode Xcode MIT

本文参考 SwiftUI 官方示例 并将探索结果记录于此,希望能够对你有所帮助。

对于本文所述内容,默认你已有一定的基于 Swift 语言的开发经验,故不会详细的叙述每个细节;如果对 Swift 语法有疑问,可先学习 Swift 语法。

有关 SwiftUI 的疑问,可加入 SwiftUI QQ 交流群:18552966 ,共同探讨。

English 📔

Whats New in SwiftUI?

截图

View Layout

💻 所需环境

  • macOS 10.15
  • Xcode 11.0
  • iOS 13.0

📂 目录:

基础控件

布局

State and Data Flow 状态和数据流

手势

基础控件

Text

Text 用来展示一行或多行的文本内容,效果等同于 UILabel,但更加优秀。 如果要创建 Text, 只需通过 Text("SwiftUI") 即可创建; 采用链式语法,也可以为文本添加多项属性,如字体、颜色、阴影、上左下右的间距等。

示例:

Text("SwiftUI")
    .foregroundColor(.orange)
    .bold()
    .font(.system(.largeTitle))
    .fontWeight(.medium)
    .italic()
    .shadow(color: .black, radius: 1, x: 0, y: 2)
查看运行效果

HStack 和 VStack 控件用于承载多个视图,在后面会提到。

🔝

TextField

TextField 用来添加普通的输入框,一般常用作文本输入。

示例:


TextField(self.$name, placeholder: self.nameText, onEditingChanged: { changed in
    print("onEditing: \(changed)")
}) {
    print("userName: \(self.name)")
    self.endEditing(true)
}}
.padding(10)
.frame(height: 50)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
查看运行效果

🔝

SecureField

SecureField 一般作为密码输入时使用,使用方式与 TextField 并无差别,示例与运行效果同上 TextField

Image

Image 控件用于展示图片。

示例:

Image("icon")
    .resizable()
    .frame(width: 100,
           height: 100,
           alignment: .center)
查看运行效果

🔝

WebImage

webImage 用于下载网络图片,使用的 URLSession下载成功后替换原有 Image;你也可以在 downloadWebImage 方法中使用 Kingfisher

示例:

var body: some View {
        Image(uiImage: self.uiImage ?? placeholderImage)
            .resizable()
            .onAppear(perform: downloadWebImage)
            .frame(width: 80,
                   height: 80,
                   alignment: .center)
            .onTapGesture {
                print("Tap ")
        }
    }
查看运行效果

🔝

Button

Button 用于响应点击事件。

示例:

Button(action: {
    print("Tap")
}) {
   Text("I'm a Button")
}

PullDownButton

尚未发布

ItemBasedPopUpButton

尚未发布

NavigationButton 已弃用

NavigationButtonPage 用以 Push 到下一个导航页面。

示例:

NavigationLink(destination: NavigationButtonPage()) {
            Text("NavigationButton").bold()
                .foregroundColor(.orange)
                .font(.largeTitle)
            }
    .navigationBarTitle(Text("Page"))
查看运行效果

🔝

PresentationButton

PresentationButton 用以弹出一个页面。 已经弃用了,请使用 NavigationLink

🔝

EditButton

EditButton 用以触发编辑状态,使用时只需在 navigationBarItems 设置即可。

示例:

navigationBarItems(trailing: EditButton())
查看运行效果

🔝

PasteButton

尚未发布

Picker

Picker 可自定义数据源的选择器。

示例:

Picker(selection: $leftIndex, label: Text("Picker")) {
    ForEach(0..<leftSource.count) {
        Text(self.leftSource[$0]).tag($0)
    }
    }.frame(width: UIScreen.main.bounds.width/2)
查看运行效果

🔝

DatePicker

DatePicker 用于选择绝对日期的控件。

示例:

DatePicker(selection: $server.date, 
                in: server.spaceDate, 
                displayedComponents: .date, label: {
                    Text("")
                })
查看运行效果

🔝

Toggle

Toggle 用于切换选中状态。

示例:

Toggle(isOn: $isOn) {
    Text("State: \(self.isOn == true ? "开":"关")")
}.padding(20)
查看运行效果

🔝

Slider

Slider 用于从有限值范围中选值的控件。

示例:

Slider(value: $data.rating)
查看运行效果

🔝

Stepper

Stepper 用以增加或减少数值。

示例:

Stepper(value: $value, step: 2, onEditingChanged: { c in
    print(c)
}) {
    Text("Stepper Value: \(self.value)")
    }.padding(50)
查看运行效果

🔝

SegmentedControl 已经弃用了

SegmentedControl 用以分段条件选择。

示例:

SegmentedControl(selection: $currentIndex) {
    ForEach(0..<items.count) { index in
        Text(self.items[index]).tag(index)
    }
    }.tapAction {
        print("currentIndex: \(self.currentIndex)")
}
查看完整示例及运行效果

🔝

WebView

WebView 用于展示一个打开的网页。

示例:

struct WebViewPage : UIViewRepresentable {
    func makeUIView(context: Context) -> WKWebView  {
        return WKWebView()
    }
    func updateUIView(_ uiView: WKWebView, context: Context) {
        let req = URLRequest(url: URL(string: "https://www.apple.com")!)
        uiView.load(req)
    }
}
查看运行效果

🔝

UIViewController

UIViewController 用于展示在 SwiftUI 中打开 UIKitUIViewController ,并且在 UIViewController 中打开 SwiftUI View。

示例:

先定义:

struct ControllerPage<T: UIViewController> : UIViewControllerRepresentable {
    
    typealias UIViewControllerType = UIViewController
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ControllerPage>) -> UIViewController {
        return T()
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<ControllerPage>) {
        debugPrint("\(#function)\(type(of: T.self))")
    }
    
}

然后调用:

NavigationButton(destination: ControllerPage<UIKitController>()) {
    PageRow(title: "UIViewController",subTitle: "打开 UIViewController")

}
查看运行效果

🔝

布局

HStack

HStack 用于将子视图排列在水平线上的视图。

示例:

HStack {
    Text("made in China.")
    Divider() // Just add a line.
    Text("the People's Republic Of China.")
}
查看运行效果

🔝

VStack

VStack 用于将子视图排列在垂直线上的视图。

示例:

VStack {
    Text("made in China.")
    Divider() // Just add a line.
    Text("the People's Republic Of China.")
}
查看运行效果

🔝

ZStack

ZStack 用于覆盖子视图,在两轴上对齐。

示例:

ZStack {
    Text("made in China.")
    Divider() // Just add a line.
    Text("the People's Republic Of China.")
}
查看运行效果

🔝

List

List 列表容器,用以显示一列数据。

示例:

List(0..<5) { item in
    Text("Hello World !")
}.navigationBarTitle(Text("List"), displayMode: .large)
查看运行效果

🔝

ScrollView

ScrollView 是一个滚动视图容器。

示例:

ScrollView {
    Text("SwiftUI").padding(20)
    Divider()
    Image("icon").resizable()
        .frame(width: 300, height: 300, alignment: .center)
    Divider()
    Text("Views and ... user interface.")
    }
    .border(Color.gray.gradient, width: 1)
            .cornerRadius(10)
            .padding(10)
            .navigationBarTitle(Text("ScrollView"))
查看运行效果

🔝

ForEach

ForEach 用于根据已有数据的集合展示视图。

示例:

let data = (0..<5)
var body: some View {
    ForEach(data) { e in
        Text("Hello \(e)")
            .bold()
            .font(.system(size: 25, design: .monospaced))
            .padding(5)
}
查看运行效果

🔝

Group

Group 用于集合多个视图,对 Group 设置的属性,将作用于每个子视图。

示例:

Group {
    Text("Hello World !")
    Text("Hello World !")
    }
查看运行效果

🔝

GroupBox

尚未发布

Section

Section 用于创建带头/尾部的视图内容,一般结合 List 组件使用。

示例:

Section(header: Text("I'm header"), footer: Text("I'm footer")) {
    ForEach(0..<3) {
        Text("Hello \($0)")
    }
}
查看运行效果

Form

Form 是对一组数据输入进行控制的容器。

Example:

Form {
   TextField("First Name", text: $firstName)
   TextField("Last Name", text: $lastName)
}
查看运行效果

🔝

NavigationView

NavigationView 用于创建包含顶部导航栏的视图容器。

示例:

NavigationView {
            Text("🧚‍♂️🧚‍♀️🧜‍♂️🧜‍♀️🧞‍♂️🧞‍♀️").blur(radius: 5)
            Text("Swifter Swifter")
            .bold()
                .foregroundColor(.orange)
                .font(.largeTitle)
        }
    .navigationBarTitle(Text("NavigationView"))
查看运行效果

🔝

TabView

TabView 用于创建包含底部 ** TabBar** 的视图容器。

示例:

TabView(selection: $index) {
    ForEach(0..<imgs.count) { item in
        TabItemPage(index: item)
            .tabItem{
                Image(self.imgs[item])
                Text("\(item)")
        }
        .tag(item)
    }
}
查看运行效果

🔝

HSplitView

尚未发布

VSplitView

尚未发布

Alert

Alert 用于展示一个弹框提醒,需要与点击事件关联起来。

示例:

alert(isPresented: $showAlert, content: {
            Alert(title: Text("确定要支付这100000000美元吗?"),
                  message: Text("请谨慎操作\n一旦确认,钱款将立即转入对方账户"),
                  primaryButton: .destructive(Text("确认")) { print("转出中...") },
                  secondaryButton: .cancel())
        }).navigationBarTitle(Text("Alert"))
查看运行效果

🔝

ActionSheet

ActionSheet 用于弹出一个选择框。

示例:

ActionSheet(title: Text("Title"),
            message: Text("Message"),
            buttons:
    [.default(Text("Default"), onTrigger: {
        print("Default")
        self.showSheet = false
    }),.destructive(Text("destructive"), onTrigger: {
        print("destructive")
        self.showSheet = false
    }),.cancel({
        print("Cancel")
        self.showSheet = false
    })])

使用:

.actionSheet(isPresented: $showSheet, content: {sheet})
查看运行效果

🔝

Modal

Modal 用于弹出一个视图。

示例:

Modal(Text("Modal View"),onDismiss: {
    print("View Dismiss !")
})
查看运行效果

🔝

Popover

Popover 用于弹出一个视图,样式见下方运行结果。

示例:

.popover(isPresented: $showPop, content: {
                ImagePage()
            })
查看运行效果

🔝

📎 About

  • 以上示例中所涉及代码,皆在本仓库代码中,建议下载并运行查看。
  • 如果有关于 SwiftUI 更好的用法与建议,期待能够一起分享!
  • 如果本文示例内容有疏漏和错误之处,欢迎提 Issue

✉️ Contacts

email : hi@jinxiansen.com

微博 : @晋先森

📄 License

SwiftUI is released under the MIT license. See LICENSE for details.

Swift
1
https://gitee.com/TheAlgorithms/SwiftUI.git
git@gitee.com:TheAlgorithms/SwiftUI.git
TheAlgorithms
SwiftUI
SwiftUI
master

搜索帮助