본문 바로가기

iOS/STUDY

[iOS] UISegmentedControl

https://developer.apple.com/tutorials/app-dev-training/filtering-reminders

 

iOS App Dev Tutorials 를 공부하고 작성한 글입니다.

 

UISegmentedControl

A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
여러 segment로 구성된 수평 컨트롤로, 각 segment는 개별 버튼으로 작동합니다.

 

- 각 컨트롤은 제목 또는 이미지(UIImage)로 표시할 수 있다고 합니다.

- UISegmentedControl 객체는 특정 width가 설정되어 있지 않은 한 super view 내에 비례적으로 맞도록  segment 크기를 자동으로 조정합니다.

- segment를 추가 및 제거할 때 sliding 및 fading 효과로 애니메이션을 적용할 수 있습니다.

 

- 'valueChanged' 이벤트가 발생할 때 target-action method를 등록해야합니다.

 

 

 

튜토리얼

위의 사진에서 Today, Future, All 버튼이 각 segment로 

Today를 누르면 오늘날짜의 Remider, Future을 누르면 오늘 이후의 Reminder, All을 누르면 모든 Reminder를 보여주도록 하는 컨트롤을 만들 것입니다. (데이터를 적용하는 부분은 다루지 않고 UISegmentedControl을 적용하는 부분만 다루겠습니다.)

 

UISegmentedControl

var listStyle: ReminderListStyle = .today
let listStyleSegmentedControl = UISegmentedControl(items: [
    ReminderListStyle.today.name, ReminderListStyle.future.name, ReminderListStyle.all.name
])

items 에 각각의 타이틀을 배열로 넣어 선언해줍니다.

 

 

viewDidLoad() 부분에 UISegmentedControl의 selectedSegmentIndex 의 인덱스 값을 선택한 세그먼트로 설정해주고,

네비게이션의 titleView를 UISegmentedControl로 설정합니다.

listStyleSegmentedControl.selectedSegmentIndex = listStyle.rawValue
navigationItem.titleView = listStyleSegmentedControl

 

UISegmentedControl.selectedSegmentIndex

The index number that identifies the selected segment that the user last touched.
사용자가 마지막으로 터치한 선택된 segment를 식별하는 index 번호입니다.

 

 

target-action method 등록

didChangeListStyle 이라는 method를 선언해주고

@objc func didChangeListStyle(_ sender: UISegmentedControl) {
    listStyle = ReminderListStyle(rawValue: sender.selectedSegmentIndex) ?? .today
    updateSnapshot()
}

 

viewDidLoad()에서 segment가 선택될 때 마다 호출하도록 등록합니다.

listStyleSegmentedControl.addTarget(self, action: #selector(didChangeListStyle(_:)), for: .valueChanged)