版本記錄
版本號 | 時間 |
---|---|
V1.0 | 2019.06.14 星期五 |
前言
SwiftUI是2019年WWDC新推出的UI相關的API顿颅,相信大家都已經知道并想體驗一下滩报,下面我們就去一起了解和學習了。感興趣的可以看下面幾篇文章妇拯。
1. SwiftUI框架解析(一) —— 基于SwiftUI的一個簡單示例(一)
源碼
首先看下工程文件組織結構
下面就是代碼了
1. SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: ContentView(rGuess: 0.5, gGuess: 0.5, bGuess: 0.5))
self.window = window
window.makeKeyAndVisible()
}
2. ContentView.swift
import SwiftUI
struct ContentView: View {
let rTarget = Double.random(in: 0..<1)
let gTarget = Double.random(in: 0..<1)
let bTarget = Double.random(in: 0..<1)
@State var rGuess: Double
@State var gGuess: Double
@State var bGuess: Double
@State var showAlert = false
func computeScore() -> Int {
let rDiff = rGuess - rTarget
let gDiff = gGuess - gTarget
let bDiff = bGuess - bTarget
let diff = sqrt(rDiff * rDiff + gDiff * gDiff + bDiff * bDiff)
return Int((1.0 - diff) * 100.0 + 0.5)
}
var body: some View {
VStack {
HStack {
// Target color block
VStack {
Rectangle()
.foregroundColor(Color(red: rTarget, green: gTarget, blue: bTarget, opacity: 1.0))
Text("Match this color")
}
// Guess color block
VStack {
Rectangle()
.foregroundColor(Color(red: rGuess, green: gGuess, blue: bGuess, opacity: 1.0))
HStack {
Text("R: \(Int(rGuess * 255.0))")
Text("G: \(Int(gGuess * 255.0))")
Text("B: \(Int(bGuess * 255.0))")
}
}
}
Button(action: {
self.showAlert = true
}) {
Text("Hit Me!")
}
.presentation($showAlert) {
Alert(title: Text("Your Score"), message: Text("\(computeScore())"))
}
VStack {
ColorSlider(value: $rGuess, textColor: .red)
ColorSlider(value: $gGuess, textColor: .green)
ColorSlider(value: $bGuess, textColor: .blue)
}
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView(rGuess: 0.5, gGuess: 0.5, bGuess: 0.5)
}
}
#endif
struct ColorSlider : View {
@Binding var value: Double
var textColor: Color
var body: some View {
return HStack {
Text("0")
.color(textColor)
Slider(value: $value, from: 0.0, through: 1.0)
Text("255")
.color(textColor)
}
.padding()
}
}
后記
本篇主要講述了SwiftUI相關壶唤,感興趣的給個贊或者關注~~~