기어가더라도 제대로
[UIKit-기초] UISegmentedControl - basic 본문
언제 사용하는가?
수평으로 구성된 여러개의 버튼을 나열하고, 각각의 버튼을 하나씩 선택된 상태로 이용하고 싶을 때 사용
- UISecmentedControl: 여러개의 파편(Segment)으로 구성된 수평 컨트롤, 각 파편은 구별된 버튼으로 기능
구현 편의를 위해, SnapKit, Then을 사용
기본 사용법
- 사용할 뷰 선언
- UISegmentedControl(items: [Any]) 아이템에 무엇을 넣는지가 레이블에 무슨 단어가 들어갈지 결정
class ViewController: UIViewController {
let segmentedControl: UISegmentedControl = {
let control = UISegmentedControl(items: ["One", "Two"])
return control
}()
let firstView = UIView().then {
$0.backgroundColor = .systemBlue
}
let secondView = UIView().then {
$0.backgroundColor = .systemGreen
}
}
- 레이아웃 선언
override func viewDidLoad() {
super.viewDidLoad()
setupLaytout()
setupAttributes()
}
func setupLayout() {
view.backgroundColor = .white
[segmentedControl, firstView, secondView].forEach {
view.addSubview($0)
}
segmentedControl.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide).inset(32)
}
[firstView, secondView].forEach { colorView in
colorView.snp.makeConstraints {
$0.top.equalTo(segmentedControl.snp.bottom).offset(16)
$0.horizontalEdges.bottom.equalToSuperview()
}
}
}
- segmented control의 상태값에 따라 어떤 화면을 보여줄 지 결정하는 코드 추가
- 세그먼트 컨트롤의 선택 인덱스 값이 0이면 FirstView, 1이면 SecondView를 보여줌
func setupAttributes() {
// segment action
segmentedControl.addTarget(
self,
action: #selector(didChangeValue(segment:)),
for: .valueChanged
)
// set default view FirstView
segmentedControl.selectedSegmentIndex = 0
didChangeValue(segment: segmentedControl)
}
/// 세그먼트 컨트롤의 상태값 변화에 따라 뷰의 Visibility를 결정
/// - Parameter segment: .selectedIndex가 현재 선택된 화면을 나타냄
@objc private func didChangeValue(segment: UISegmentedControl) {
self.shouldSecondViewHidden = segment.selectedSegmentIndex == 0
}
- 세그먼트 컨트롤의 값이 변화하면 옵셔널 불 값을 업데이트
/// 어떤 화면을 보여줄지 상태값을 나타냄
var shouldSecondViewHidden: Bool? {
didSet {
guard let shouldSecondViewHidden else { return }
firstView.isHidden = !shouldSecondViewHidden
secondView.isHidden = shouldSecondViewHidden
}
}
전체 코드
https://github.com/Damagucci-Juice/ExSegmentedControl
GitHub - Damagucci-Juice/ExSegmentedControl
Contribute to Damagucci-Juice/ExSegmentedControl development by creating an account on GitHub.
github.com
참조
https://developer.apple.com/documentation/uikit/uisegmentedcontrol
UISegmentedControl | Apple Developer Documentation
A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
developer.apple.com
https://ios-development.tistory.com/962
[iOS - swift] 1. UISegmentedControl - 기본 사용 방법
1. UISegmentedControl - 기본 사용 방법 2. UISegmentedControl - 커스텀 방법, PageViewController와 사용 방법 UISegmenetedControl 사용 방법 Swift에는 Radio Button이 따로 없고 UISegmentedControl이 존재 ViewController 준비 import
ios-development.tistory.com