본문 바로가기
Projects/Swift

Swift :: 버스시간표 앱을 만들기 - 3 [ 데이터 추가 ]

by 앱병찬 2024. 12. 3.

 

MYS_Dir()과 PNU_Dir()에 비어있는 버스정보 데이터 키 값(대학 방학, 모두 방학)을 모두 넣어줬다.

let schedules = [
        "대학 개강": [
            ["버스 노선", "부산대", "밀양역"],
            ["7번", "07:02", "07:18"],
            ["2번", "07:20", "07:32"],
            ...
        ],
        "대학 방학": [
            ["버스 노선", "부산대", "밀양역"],
            ["2번", "07:20", "07:35"],
            ["1번", "08:40", "09:05"],
            ...
        ],
        "모두 방학": [
            ["버스 노선", "부산대", "밀양역"],
            ["7번", "07:02", "07:18"],
            ["2번", "07:20", "07:32"],
            ...
        ]
    ]

 


 

ScrollView{
                LazyVGrid(columns: columns, spacing: 20) {
                    if let schedule = schedules[selectedSchedule] {
                        ForEach(schedule.indices, id: \.self) { rowIndex in
                            createRow(row: schedule[rowIndex], rowIndex: rowIndex)
                        }
                    }
                }
                .padding()
            }

위의 코드는 이 전 ScrollView이다

 

List 컴포넌트

헤더 행

HStack {
    ForEach(schedule.first ?? [], id: \.self) { header in
        Text(header)
            .fontWeight(.bold)
            .frame(maxWidth: .infinity, alignment: .center)
    }
}
.padding(.vertical, 5)
.background(Color.gray.opacity(0.2))

 

schedule.first ?? []: 시간표의 첫 번째 행(헤더)을 가져옴

HStack: 헤더를 가로로 나란히 배치

.padding(.vertical, 5): 위, 아래로 5포인트 패딩 추가

 

데이터 행

ForEach(schedule.dropFirst(), id: \.self) { row in
    HStack {
        ForEach(row, id: \.self) { cell in
            Text(cell)
                .frame(maxWidth: .infinity, alignment: .center)
        }
    }
    .padding(.vertical, 5)
    .background(
        schedule.firstIndex(of: row)! % 2 == 0 ?
        Color.blue.opacity(0.1) :
            Color.clear
    )
}
.listStyle(PlainListStyle())

 

.schedule.dropFirst() : 첫 번째 행(헤더)을 제외한 나머지 행들을 가져온다

HStack - 각 행(row)은 가로로 배치

schedule.firstIndex(of: row)! % 2 == 0 ? Color.blue opacity(0.1) : Color.clear

-> 행의 인덱스가 짝수면 배경을 파란색으로, 홀수면 Clear 배경 적용

.lifeStyle(PlainListStyle())

-> 리스트의 스타일을 PlainListStyle로 설정 ( 기본 스타일보다 간결)

else {
                Text("선택한 시간표가 없습니다.")
                    .foregroundColor(.gray)
            }

선택된 시간표가 없을 경우, 회색 텍스트로 에러 메시지 표시