SwiftUI ListView 1- 인덱스 번호 표시, 컬럼 색 변경
1. SwiftUI에서 리스트뷰 인덱스 번호 나오게 하는 방법
import SwiftUI
struct Friend: Identifiable{
let id = UUID()
let name:String
}
struct ContentView: View {
let friends = [Friend(name: "John"), Friend(name: "Mary"), Friend(name: "Steven")]
var body: some View {
List(friends.indices){ index in
let friend = friends[index]
HStack {
Text("\(index+1)")
Text(friend.name)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
2. 컬럼 백그라운드 칼러 바꾸기
import SwiftUI
struct ContentView: View {
let animals = ["dog", "horse", "cow", "monkey", "rabbit", "pig", "hippo"]
var body: some View {
List(animals.indices, id:\.self){ index in
let animal = animals[index]
HStack {
Text("\(index+1)")
Text(animal)
.font(.largeTitle)
Spacer()
}
.background(index % 2 == 0 ? Color.blue: Color.green)
//.background(Color.red)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}