본문 바로가기

iOS 앱 개발자 프로젝트/iOS 입문

[iOS] UIView component #2 (UISlider, UISegmentedControl, UIScrollView, UIPickerView, UITableView, UICollectionView)

2024년 3월 19일 화요일 #2

 


 

UISlider (값의 범위를 가지고 사용자가 원하는 값을 선택)
  • value: 슬라이더의 현재 값
  • minimumValue: 슬라이더의 최소값을 설정
  • maximumValue: 슬라이더의 최대값을 설정
  • minimumTrackTintColor: 슬라이더의 왼쪽 트랙 색상을 설정
  • maximumTrackTintColor: 슬라이더의 오른쪽 트랙 색상을 설정
  • thumbTintColor: 슬라이더의 썸네일 색상을 설정
// UISlider 생성 및 설정  
let slider = UISlider()  
slider.value = 50 // 슬라이더 초기 값 설정  
slider.minimumValue = 0 // 슬라이더의 최소값 설정  
slider.maximumValue = 100 // 슬라이더의 최대값 설정  
slider.minimumTrackTintColor = UIColor.red // 왼쪽 트랙 색상 설정  
slider.maximumTrackTintColor = UIColor.blue // 오른쪽 트랙 색상 설정  
slider.thumbTintColor = UIColor.white // 썸네일 색상 설정  
  
// 슬라이더 값 변경 이벤트 처리  
slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)  
  
@objc func sliderValueChanged(_ sender: UISlider) {  
    print("Slider value: \(sender.value)")  
}

 

 

UISegmentedControl (여러 개의 세그먼트로 구성된 컨트롤, 각 세그먼트를 선택하여 원하는 옵션을 선택)
  • selectedSegmentIndex: 현재 선택된 세그먼트의 인덱스
  • numberOfSegments: 세그먼트의 개수
  • tintColor: 세그먼트 컨트롤의 색상을 설정
  • isMomentary: 세그먼트가 선택되었을 때 선택 표시를 유지할지 여부를 설정
// UISegmentedControl 생성 및 설정  
let items = ["Option 1", "Option 2", "Option 3"]  
let segmentedControl = UISegmentedControl(items: items)  
segmentedControl.selectedSegmentIndex = 0 // 초기 선택된 세그먼트 인덱스 설정  
segmentedControl.tintColor = UIColor.blue // 세그먼트 컨트롤 색상 설정  
segmentedControl.isMomentary = false // 선택 표시를 유지할지 여부 설정  
  
// 세그먼트 값 변경 이벤트 처리  
segmentedControl.addTarget(self, action: #selector(segmentValueChanged(_:)), for: .valueChanged)  
  
@objc func segmentValueChanged(_ sender: UISegmentedControl) {  
    print("Selected segment index: \(sender.selectedSegmentIndex)")  
}

 

 

UIScrollView (화면에서 스크롤 가능한 영역을 제공)
  • contentSize: 스크롤 영역의 크기. 이 값이 UIScrollView의 프레임 크기보다 크면 스크롤이 가능
  • contentOffset: 스크롤 뷰의 현재 스크롤 위치
  • contentInset: 스크롤 뷰의 컨텐츠와 뷰 사이의 여백을 설정
  • isScrollEnabled: 스크롤 기능을 활성화 또는 비활성화
  • isPagingEnabled: 페이지 기능을 활성화/비활성화. 활성화되면 스크롤 시 한 페이지씩 이동. 기본값은 false
  • bounces: 스크롤 뷰가 컨텐츠의 경계에 도달했을 때 바운스 효과를 활성화/비활성화
// UIScrollView 생성 및 설정
let scrollView = UIScrollView(frame: view.bounds)  
scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height * 2)  
scrollView.isScrollEnabled = true  
scrollView.isPagingEnabled = false  
scrollView.bounces = true

// 스크롤 뷰에 추가할 UILabel  
let label = UILabel(frame: CGRect(x: 0, y: view.frame.height - 30, width: view.frame.width, height: 60))  
label.text = "Hello, UIScrollView!"  
label.textAlignment = .center
scrollView.addSubview(label)

 

 

UIPickerView (여러 개의 옵션 중 하나를 선택할 수 있는, 회전 가능한 휠 형식 UI 요소)
  • dataSource: UIPickerView의 데이터를 제공하는 객체를 설정
  • delegate: UIPickerView의 이벤트를 처리하는 객체를 설정
  • numberOfComponents: UIPickerView에서 표시할 구성 요소의 수를 반환
  • selectedRow(inComponent:): 지정된 구성 요소에서 선택된 행의 인덱스를 반환
import UIKit  
  
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {  
      
    let pickerView = UIPickerView()  
    let data = ["Option 1", "Option 2", "Option 3"]  
      
    override func viewDidLoad() {  
        super.viewDidLoad()  
          
        pickerView.delegate = self  
        pickerView.dataSource = self  
        pickerView.center = view.center  
        view.addSubview(pickerView)  
    }  
      
    // UIPickerViewDataSource  

		/* [필수] Component 수를 보고합니다. */
		// Component는 섹션의 개념과 유사합니다. UIPickerView는 여러 열(구성 요소)을 가질 수 있습니다.
    func numberOfComponents(in pickerView: UIPickerView) -> Int {  
        return 1  
    }  
    
		/* [필수] component에 따른 행 수를 보고합니다. */
		// component: 0부터 시작합니다.
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {  
        return data.count  
    }  
      
    // UIPickerViewDelegate  
		
		/* row와 component조합으로 표시될 선택지를 return합니다. */
		// row: 0부터 시작합니다.
		// component: 0부터 시작합니다.
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {  
        return data[row]  
    }  
      
		/* 선택지가 선택되었을 때 호출 */
	  // row: 0부터 시작합니다. / 선택된 row
		// component: 0부터 시작합니다. / 선택된 component
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {  
        print("Selected: \(data[row])")  
    }  
}

 

 

UITableView (데이터 목록을 표시, 상호 작용할 수 있는 스크롤 가능한 UI 요소)
  • dataSource: UITableView의 데이터를 제공하는 객체를 설정
  • delegate: UITableView의 이벤트를 처리하는 객체를 설정
  • rowHeight: 각 행의 높이를 설정
  • separatorStyle: 행 간 구분선의 스타일을 설정
  • separatorColor: 행 간 구분선의 색상을 설정
  • allowsSelection: 테이블 뷰에서 행 선택을 허용할지 여부를 설정
import UIKit
  
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {  
      
    let tableView = UITableView()  
    let data = ["Item 1", "Item 2", "Item 3"]  
      
    override func viewDidLoad() {  
        super.viewDidLoad()  
          
        tableView.frame = view.bounds  
        tableView.dataSource = self  
        tableView.delegate = self  
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")  
        view.addSubview(tableView)  
    }  
      
    // UITableViewDataSource
		
		/* [필수] 테이블의 행 수를 보고합니다. */
		// section: 테이블뷰의 section을 나타내는 식별자 입니다. 이를 바탕으로 해당 섹션의 count를 반환합니다.
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {  
        return data.count  
    }  
    
		/* [필수] 테이블의 각 행에 대한 셀을 제공합니다. */
		// indexPath: 테이블뷰에서 Row(행)을 찾는 경로입니다. 이를 바탕으로 적절한 cell을 반환합니다.
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)  
        cell.textLabel?.text = data[indexPath.row]  
        return cell  
    }  
      
    // UITableViewDelegate
		
		/* 행이 선택되었을 때 호출 */
		// indexPath: 테이블뷰에서 선택된 Row(행)을 찾는 경로입니다. 이를 바탕으로 어떤 행이 선택되었는지 파악할 수 있습니다.
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {  
        print("Selected: \(data[indexPath.row])")  
        tableView.deselectRow(at: indexPath, animated: true)  
    }  
}

 

 

UICollectionView (유연한 그리드 레이아웃을 사용, 아이템 목록을 표시, 상호 작용할 수 있는 스크롤 가능한 UI 요소)
  • dataSource: UICollectionView의 데이터를 제공하는 객체를 설정
  • delegate: UICollectionView의 이벤트를 처리하는 객체를 설정
  • collectionViewLayout: UICollectionView의 레이아웃을 설정
  • allowsSelection: 컬렉션 뷰에서 셀 선택을 허용할지 여부를 설정
  • allowsMultipleSelection: 여러 셀을 동시에 선택할 수 있는지 여부를 설정
import UIKit  
  
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {  
      
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())  
    let data = ["Item 1", "Item 2", "Item 3"]  
      
    override func viewDidLoad() {  
        super.viewDidLoad()  
          
        collectionView.frame = view.bounds  
        collectionView.dataSource = self  
        collectionView.delegate = self  
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")  
        collectionView.backgroundColor = .white  
        view.addSubview(collectionView)  
    }  
      
    // UICollectionViewDataSource 

		/* [필수] 행 수를 보고합니다. */
		// section: 컬렉션뷰의 section을 나타내는 식별자 입니다. 이를 바탕으로 해당 섹션의 count를 반환합니다.
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {  
        return data.count  
    }  
    
		/* [필수] 각 행에 대한 셀을 제공합니다. */
		// indexPath: 컬렉션뷰에서 Row(행)을 찾는 경로입니다. 이를 바탕으로 적절한 cell을 반환합니다.
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {  
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)  
        cell.backgroundColor = .blue  
        return cell  
    }  
      
    // UICollectionViewDelegate

		/* 행이 선택되었을 때 호출 */
		// indexPath: 컬렉션뷰에서 선택된 Row(행)을 찾는 경로입니다. 이를 바탕으로 어떤 행이 선택되었는지 파악할 수 있습니다.
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {  
        print("Selected: \(data[indexPath.row])")  
        collectionView.deselectItem(at: indexPath, animated: true)  
    }  
      
    // UICollectionViewDelegateFlowLayout

		/* 셀의 크기를 보고합니다 */
		// collectionViewLayout: 컬렉션뷰에서 사용된 레이아웃입니다. 행의 크기를 반환할 때 참고할 수 있습니다.
    // indexPath: 컬렉션뷰에서 선택된 Row(행)을 찾는 경로입니다. 이를 바탕으로 어떤 행의 크기를 반환할지 판단할 수 있습니다.
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {  
        return CGSize(width: 100, height: 100)  
    }  
}