dev._.note

[Swift-UI] UIView 컴포넌트 본문

Dev/SWIFT UI

[Swift-UI] UIView 컴포넌트

Laena 2023. 12. 19. 16:28

UIView 컴포넌트

UIView는 iOS에서 사용되는 기본적인 뷰 컴포넌트로 다른 UI 컴포넌트들은 이 UIView를 상속받아서 필요한 기능을 추가하거나 확장한 컴포넌트.

📌 UILabel

텍스트를 표시하는 데 사용되는 UI 요소

 

UILabel의 주요 속성들

  • text: 표시할 문자열을 나타냄.
  • font: 텍스트의 폰트를 설정.
  • textColor: 텍스트의 색상을 설정.
  • textAlignment: 텍스트의 정렬을 설정. (왼쪽, 가운데, 오른쪽)
  • numberOfLines: 텍스트의 표시 줄 수를 설정. (0으로 설정하면 자동으로 줄 바꿈)
  • lineBreakMode: 텍스트가 너무 길어서 화면에 들어가지 않을 때 줄 바꿈 처리 방법을 설정.
let label = UILabel()
label.text = "안녕하세요"
label.font = UIFont.systemFont(ofSize: 18) // 폰트 크기 설정
label.textColor = UIColer.black // 텍스트 색상 설정
label.textAlignment = .center // 가운데 정렬
label.numberOfLines = 2 // 최대 2줄까지 표시 (0으로 설정하면 자동 줄바꿈)
label.lineBreakMode = .byTruncatingTail // 텍스트가 너무 길 때 끝에 ...을 표시하고 줄 바꿈

📌 UIImageView

이미지를 표시하는데 사용되는 UI 요소

 

UIImageView의 주요 속성들

  • image: 표시할 이미지를 설정. 이 속성에는 UIImage 객체를 할당.
  • contentMode: 이미지가 UIImageView에 맞춰질 때의 크기 및 배치 방법을 설정. 예를 들어,. scaleAspectFit은 이미지를 UIImageView에 맞추고 비율을 유지.
    • scaleToFill: 이미지가 원래 비율을 무시하고 이미지 뷰의 경계에 맞춰 이미지를 확장
    • scaleAspectFit: 이미지의 가로세로 비율을 유지하면서 이미지 뷰에 맞춰 가능한한 많은 공간을 차지하도록 이미지를 확장
    • scaleAspectFill: 이미지의 가로세로 비율을 유지하면서 이미지 뷰를 완전히 채우도록 이미지를 확장 (이미지가 잘릴 수 있음.)
    • reddraw: 이미지 뷰의 경계가 변경될 때마다 이미지 뷰를 다시 그림.
    • center, top, bottom, left, right, topRight, topLeft, bottomRight, bottomLeft: 이미지를 이미지 뷰의 해당 위치에 배치하고 이미지 크기는 변경되지 않으며 이미지가 이미지 뷰의 경계를 넘을 경우 잘릴 수 있음.
  • isUserInteractionEnabled: 사용자 상호 작용을 허용할지 여부를 나타냄. 기본적으로 false*로 설정되어 있어 사용자의 터치 이벤트를 무시.
  • animationImages: 애니메이션을 위한 이미지 배열을 설정. 이 배열에 여러 UIImage 객체를 할당하여 애니메이션을 만들 수 있음.
// UIImageView 생성 및 이미지 설정
let imageView = UIImageView()
let image = UIImage(named: "exampleImage") // 이미지 파일명으로 UIImage 객체 생성
imageView.image = image

// 이미지 뷰의 프레임 설정 (위치와 크기)
imageView.frame = CGRect(x: 50, y: 100, width: 200, height: 150)

// contentMode 설정 (이미지가 뷰에 맞춰지는 방법)
imageView.contentMode = .scaleAspectFit // 이미지의 비율을 유지하며 이미지 뷰에 맞춤

📌 UITextField

사용자로부터 텍스트를 입력받기 위해 사용되는 UI 요소

 

UITextField의 주요 속성들

  • ext: 텍스트 필드에 표시되는 문자열을 나타냅니다.
  • placeholder: 텍스트 필드에 입력을 유도하기 위해 표시되는 플레이스홀더 텍스트를 설정합니다.
  • keyboardType: 사용자가 텍스트 필드에 입력할 때 표시되는 키보드의 유형을 설정합니다. (숫자, 이메일 주소, URL 등)
  • isSecureTextEntry: 입력된 텍스트를 숨기기 위해 true로 설정하면, 입력된 텍스트가 마스킹 처리됩니다. (보통 비밀번호 입력에 사용)
  • delegate: 텍스트 필드의 동작을 관리하기 위한 델리게이트 객체를 설정합니다.
  • returnKeyType: 키보드의 리턴(엔터) 키의 타입을 설정합니다. (Done, Go, Search 등)
// UITextField 생성 및 설정
let textField = UITextField()
textField.placeholder = "텍스트를 입력하세요." // 입력 유도 메시지
textField.borderStyle = .roundedRect // 텍스트 필드의 모양 (둥근 테두리)
textField.keyboardType = .default // 일반 텍스트 입력용 키보드
textField.isSecureTextEntry = false // 보안 입력 (비밀번호 등) 여부
textField.returnKeyType = .done // 리턴(엔터) 키의 종류

📌 UIButton

사용자가 터치하여 상호작용할 수 있는 UI 요소

 

UIButton의 주요 속성들

  • titleLabel: 버튼에 표시되는 텍스트 레이블에 대한 접근을 제공. 버튼의 텍스트나 스타일을 조절하는 데 사용.
  • setImage(_:for:): 버튼에 이미지를 설정하고 상태에 따라 다른 이미지를 사용할 수 있음.
  • setTitle(_:for:): 버튼에 텍스트를 설정하고 상태에 따라 다른 텍스트를 사용할 수 있음.
  • addTarget(_:action:for:): 버튼이 터치되었을 때 실행할 액션을 등록. 이것을 사용하여 버튼의 동작을 정의할 수 있음.
  • isEnabled: 버튼이 활성화되었는지 여부를 나타내는 bool값. 비활성화된 버튼은 터치 또는 클릭 이벤트를 무시.
let button = UIButton(type: .system) // 시스템 스타일의 버튼 생성
button.setTitle("버튼을 눌러보세요", for: .normal) // 버튼에 표시될 텍스트
button.backgroundColor = UIColor.blue // 버튼 배경색 설정
button.setTitleColor(UIColor.white, for: .normal) // 버튼 텍스트 색상 설정
button.frame = CGRect(x: 50, y: 100, width: 200, height: 50) // 버튼의 프레임 설정 (위치와 크기)

// 버튼에 대한 액션 설정 (버튼이 탭되었을 때 실행될 함수)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

@objc func buttonTapped() {
  print("버튼이 눌렸습니다!")
}

📌 UISwitch

On/Off 상태를 표시하고 전환하는데 사용되는 UI 요소

 

UISwitch의 주요 속성들

  • isOn: 스위치의 현재 상태를 나타냄.
  • onTintColor: 스위치가 켜져있을 때의 배경 색상을 설정.
  • thumbTintColor: 스위치의 썸네일 색상을 설정.
// UISwitch 생성 및 설정  
let mySwitch = UISwitch()  
mySwitch.isOn = true // 스위치 초기 상태 설정  
mySwitch.onTintColor = UIColor.green // 켜져있을 때의 배경 색상 설정  
mySwitch.thumbTintColor = UIColor.white // 썸네일 색상 설정
  
// 스위치 상태 변경 이벤트 처리  
mySwitch.addTarget(self, action: #selector(switchValueChanged(_:)), for: .valueChanged)  
  
@objc func switchValueChanged(_ sender: UISwitch) {  
    if sender.isOn {  
        print("Switch is On")  
    } else {  
        print("Switch is Off")  
    }  
}

📌 UISlider

값의 범위를 가지고 사용자가 원하는 값을 선택할 수 있는 UI 요소

 

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

여러 개의 세그먼트로 구성된 컨트롤로, 각 세그먼트를 선택하여 원하는 옵션을 선택할 수 있는 UI 요소

 

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

UIScrollView는 화면에서 스크롤 가능한 영역을 제공하는 UI 요소

 

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 요소

 

UIPickerView의 주요 속성들

  • 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

UITableView는 데이터 목록을 표시하고 사용자와 상호 작용할 수 있는 스크롤 가능한 UI 요소

 

UITableView의 주요 속성들

  • 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

UICollectionView는 유연한 그리드 레이아웃을 사용하여 아이템 목록을 표시하고 사용자와 상호 작용할 수 있는 스크롤 가능한 UI 요소

 

UICollectionView의 주요 속성들

  • 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)  
    }  
}