SwiftUI는 class를 사용하는 UIKit과 달리 struct를 사용해서 간단하고 강력하다.
SwiftUI view들은 보이는 게 전부이고, 숨겨진 영역이 없다. 다시 말해 view와 modifier만으로 설계한다.
ModifiedContent type을 스택처럼 쌓아 표현하는 것이기에 modifier의 순서는 중요하다.
예:
![]() | ![]() |
---|
![]() | ![]() |
---|
// 왼쪽 이미지
struct ContentView: View {
var body: some View {
Button(action: {
print(type(of: self.body))
}, label: {
Text("This is a Text")
})
.font(.largeTitle)
.background(.green)
.frame(width: 300, height: 300)
}
}
// 오른쪽 이미지
struct ContentView: View {
var body: some View {
Button(action: {
print(type(of: self.body))
}, label: {
Text("This is a Text")
})
.font(.largeTitle)
.frame(width: 300, height: 300)
.background(.green)
}
}
View protocol을 따르는 ContentView는 ViewBuilder인 body를 작성해야 하고, 이는 some View를 리턴한다. View면 Text, VStack 등을 반환할 수 있으나, 이를 명확히 정하지 않고 View 중 하나를 전달하겠다는 의미로 some View
라고 작성한다.
ternary operator를 사용해서 조건 modifier를 사용하는 것이 if문을 활용하는 것보다 효율적이다.
예:
struct ContentView: View {
@State private var showRedBackground = false
var body: some View {
Button(action: {
showRedBackground.toggle()
}, label: {
Text("This is a Text")
})
.font(.largeTitle)
.foregroundColor(showRedBackground ? .red : .green)
}
}
예:
![]() | ![]() |
---|
// 왼쪽 이미지
struct ContentView: View {
var body: some View {
HStack {
Text("안녕하세요")
.font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
Text("Hello")
Text("Hola")
Text("Guten Tag")
}
.font(.subheadline) // environment modifier
}
}
// 오른쪽 이미지
struct ContentView: View {
var body: some View {
HStack {
Text("안녕하세요")
.blur(radius: 0)
Text("Hello")
Text("Hola")
Text("Guten Tag")
}
.blur(radius: 3) // regular modifier
}
}
struct ContentView: View {
var text1: some View {
Text("this is text1")
}
let text2 = Text("this is text2")
var text3: some View {
Group {
Text("this is text3")
Text("this is text3")
}
}
@ViewBuilder var text4: some View {
Text("this is text4")
Text("this is text4")
}
var body: some View {
text1
text2
text3
text4
}
}
예: View에 watermark 나타내기
struct Watermark: ViewModifier {
var text: String
func body(content: Content) -> some View {
ZStack(alignment: .topLeading) {
content
Text(text)
.font(.caption)
.foregroundStyle(.white)
.padding(5)
.background(.black.opacity(0.5))
}
}
}
extension View {
func watermarked(with text: String) -> some View {
modifier(Watermark(text: text))
}
}
struct ContentView: View {
var body: some View {
Image(systemName: "pencil")
.resizable()
.scaledToFit()
.watermarked(with: "This is watermark")
.padding()
}
}
코드 파일 (history에 순서대로 버전 기록함)
https://github.com/treesofgroo/Ios-studying/commit/71638c30084f227c1876bbbb34d446a3e905f85c