版本记录
版本号 | 时间 |
---|---|
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相关,感兴趣的给个赞或者关注~~~
网友评论