적당한 고통은 희열이다

- 댄 브라운 '다빈치 코드' 중에서

Project/ToyProject_Couple App

[Swift iOS] tableView 안에 Date Picker 넣는 법?

hongssup_ 2021. 3. 14. 12:36
반응형

달력에 일정을 추가하기 위해 Date Picker로 날짜를 선택할 수 있는 cell을 만들어보았다. 

cell 에 들어가는 item들을 배열로 설정할 경우, 

var items = ["날짜", "", "시간", "위치"]

이렇게 Date Picker가 들어갈 자리를 빈 cell 로 설정하여, 날짜 cell 을 터치 시 나타나고 default 값으로는 숨어서 보이지 않는 형태로 만들어 볼 것이다.

 

1. UIDatePicker() 추가하기

DatePickerCell을 UITableViewCell 클래스로 따로 만들어 넣어주는 방법도 있던데, 나는 섹션도 여러개고 행도 여러개이기 때문에 cell 마다 클래스를 따로 만들어주면 너무 복잡할 것 같아서 그냥 내부에서 설정해주었다. 

var datePicker = UIDatePicker()

2. viewDidLoad() 에서 datePicker 속성 설정

클래스의 전역변수로 let dateFormatter = DateFormatter() 를 선언해주면 날짜를 깔끔하게 띄울 수 있다. (2021.03.14)

datePicker.date = Date()
dateFormatter.dateFormat = "yyyy.MM.dd"
dateLabel.text = "\(dateFormatter.string(from: datePicker.date))"
datePicker.isHidden = true

요일도 추가하고 싶다면 eeee (월요일) 혹은 eee (월) 로 나타낼 수 있다. (날짜 표기법 참고 : Date field symbol table

 

3. tableView cell 높이 설정

평소에는 cell의 높이를 0.0으로 설정하여 보이지 않다가, datePicker.isHidden 이 false 가 되면 높이를 216.0으로 변경하여 datePicker가 들어갈 자리를 마련해준다. (44는 tableView cell 의 기본 높이)

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 1 {
        let height:CGFloat = datePicker.isHidden ? 0.0 : 216.0
        return height            
    } else {
        return 44
    }
}

4. cell 선택시 이벤트 설정

날짜 cell을 터치하면 숨어있던 datePicker가 나타나는 애니메이션을 추가해준다. 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let dpIndexPath = NSIndexPath(row: 0, section: 0)
    if dpIndexPath as IndexPath == indexPath {
        datePicker.isHidden = !datePicker.isHidden
            
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.tableView.beginUpdates()
            self.tableView.deselectRow(at: indexPath, animated: true)
            self.tableView.endUpdates()
        })
    }
}

5. dateLabel에 날짜 업데이트

date picker를 띄우는 것 까지는 했는데 dateLabel에 글자가 업데이트되지 않는다... 이 부분은 더 고민을 해보아야 겠다.

@objc func dateChanged(sender: UIDatePicker) {
    dateLable.text = "\(dateFormatter.string(from: datePicker.date))"
}

뷰 컨트롤러 내에 dateChanged 메서드를 선언해주고 

tableView의 didSelectRowAt 안에 self.tableView.endUpdates() 하기 전에 

self.dateChanged(sender: self.datePicker)

를 넣어 주었더니 date Picker 선택을 하고 Picker cell 을 닫으면 pickerLabel text 가 업데이트 된다. :)

 

6. Date Picker 속성 추가 설정

 

- datePickerMode :

datePicker.datePickerMode = .date

나는 날짜랑 시간을 따로 설정하도록 하고 싶어서 .date 모드로 설정을 해주었는데

datePickerMode에는 .countDownTimer / .date / .dateAndTime / .time 이렇게 네가지 모드가 있다. 

 

- preferredDatePickerStyle :

if #available(iOS 14.0, *) {
    datePicker.preferredDatePickerStyle = .wheels
} 

preferredDatePickerStyle 종류에는 .automatic / .compact / .inline / .wheels 가 있는데

새로 업데이트된 기능인 듯 하다. 우리가 흔히 생각하는 datePicker로는 .wheels 를 사용하면 되는데, 예전에는 굳이 스타일을 설정해주지 않아도 이게 디폴트였다면, 이제는 이 스타일을 따로 설정해주지 않으면 이상한 달력이 팝업으로 떠서 깜짝 놀랬다. ㅋㅋㅋㅋ 

iOS 14 이상이라면 이 구문을 넣어주기. 

새로운 date picker에 대해 더 알고 싶다면 참고 ☞ new date picker

 

- 한국어 모드 설정 : 

datePicker.locale = Locale(identifier: "ko-KR")

기본은 영어로 설정되어 있고, 한국처럼 년 / 월 / 일 이 아니라 월 / 일 / 년 으로 표기되기 때문에 locale을 한국으로 설정해준다. 

혹시 이렇게 설정을 해주었는데도 한국어로 표기가 안되고 영어로 나온다면

Info.plist에서 [Information Property List - Localizaton native development region] 의 값을 Korea로 바꿔주면 된다. 

 

 

참고 사이트: stackoverflow

728x90
반응형