[Udemy iOS & Swift Bootcamp] SwiftUI Layout Design - Spacers, Subviews (SwiftUI ๋ก ๊ธฐ๋ฅ์ด ์๋ ์ฑ ๋ง๋ค๊ธฐ)
๊ธฐ์กด์ ๋ง๋ค์๋ Dice ์ฑ์ SwiftUI ๋ฅผ ํ์ฉํด์ ๋ค์ ๋ง๋ค์ด๋ณด์.
1. ์ด๋ฏธ์ง Asset ์ถ๊ฐ
https://drive.google.com/uc?export=download&id=1IubA1ewlMRNRh9JKDAT4DY4fMbZONX9j
image asset์ ๋ค์ด๋ฐ์์ Assets ํ์ผ์ import ํด์ค๋ค.
๊ฐ ๋จ๋ง๊ธฐ์ ๋ง๊ฒ ์์์ ๋ง์ถฐ ๋ค์ด๊ฐ ์๋ image ๋ค...
2. ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง ์ถ๊ฐํ๊ธฐ
1) ContentView ์ ์ด๊ธฐ ๋ชจ์ต์ ๋ฐฐ๊ฒฝ image ์ฝ๋ ์ถ๊ฐํ๊ธฐ.
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
ContentView ์ default ๋ชจ์ต
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
ZStack ๊ณผ Image๋ฅผ ์ถ๊ฐํ ๋ชจ์ต
2) ์ถ๊ฐ UI ๋ฐฐ์นํ๊ธฐ
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
VStack{
Image("diceeLogo")
Spacer()
HStack{
DiceView(n: 1)
DiceView(n: 1)
}
.padding(.horizontal)
Spacer()
Button(action:{
}){
Text("Roll")
.font(.system(size: 50))
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.horizontal)
}
.background(Color.red)
}
}
}
}
struct DiceView: View{
let n: Int
var body: some View{
Image("dice\(n)")
.resizable()
.aspectRatio(1, contentMode: .fit)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
3) ๋ฒํผ์ ๊ธฐ๋ฅ ์ถ๊ฐ
import SwiftUI
struct ContentView: View {
@State var leftDiceNumber = 1
@State var rightDiceNumber = 1
var body: some View {
ZStack {
Image("background")
.resizable()
.edgesIgnoringSafeArea(.all)
VStack{
Image("diceeLogo")
Spacer()
HStack{
DiceView(n: leftDiceNumber)
DiceView(n: rightDiceNumber)
}
.padding(.horizontal)
Spacer()
Button(action:{
self.leftDiceNumber = Int.random(in: 1...6)
self.rightDiceNumber = Int.random(in: 1...6)
}){
Text("Roll")
.font(.system(size: 50))
.fontWeight(.heavy)
.foregroundColor(.white)
.padding(.horizontal)
}
.background(Color.red)
}
}
}
}
struct DiceView: View{
let n: Int
var body: some View{
Image("dice\(n)")
.resizable()
.aspectRatio(1, contentMode: .fit)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
cf) @State ์์ฑ ์์๋ณด๊ธฐ
๋ณ์๊ฐ์ ์ ๋ฐ์ดํธํ ๋๋ง๋ค ๋ณ์๊ฐ, ContentView ๋ฅผ ์ ๋ฐ์ดํธํ๋ค.
https://developer.apple.com/documentation/swiftui/state
State | Apple Developer Documentation
A property wrapper type that can read and write a value managed by SwiftUI.
developer.apple.com