Swift/TIL(TodayILearned)

[Swift|TIL] 240318~0319 - UIViewComponents

yurim-dev 2024. 3. 19. 17:27

🕹️ UIViewController

- UIViewController는 UIKit 앱의 View 계층을 관리하는 개체(object)이다.

- UIViewController 클래스는 다양한 UIView 요소들을 포함하고 관리(제어)할 수 있다.

  (UIView 요소 예시: UILabel, UIButton, UIImageView 등)

- 모든 UIViewController는 하나의 Root View를 가지고 있으며, UIView 요소를 포함한다.

ViewController와 해당 View 간의 관계 - 출처 Apple

 


📱 UIView

- UIView는 화면을 구성하는 기본 객체(object)이다.

- 화면에 보이는 모든 요소의 기본 클래스이다. (iOS에서 사용되는 기본적인 뷰 컴포넌트)

  (UILabel, UIButton, UIImageView 등의 요소들은 모두 UIView의 하위 객체(object))


 

🔠 UIViewComponents

UIView는 iOS에서 사용되는 기본적인 뷰 컴포넌트이고,

아래 컴포넌트들은 모두 UIView 클래스를 상속받아서 필요한 기능을 추가하거나 확장한 컴포넌트이다.

 

🔹 UILabel

- 정의: 텍스트를 표시하는 데 사용되는 UI 요소

- 주요 속성: text, font, textColor, textAlignment, numberOfLines, lineBreakMode

 

LineBreakMode 일부 예시
label.text = "안녕하세요, UILabel 예제입니다. \n만나서 반갑습니다.ㅎㅎㅎㅎ" 
.byCharWrapping
: 문자 기준으로 잘림
.byWordWrapping
: 단어 기준으로 잘림
.byClipping
: 텍스트 컨테이너를 지나서 확장되지 않음
.byTruncatingTail
: 텍스트가 길 때 꼬리 부분이 잘리고 ... 으로 표현됨.
 

 


🔹 UIImageView

- 정의: 이미지를 표시하는 데 사용되는 UI 요소

- 주요 속성: image, contentMode, isUserInteractionEnabled, animationImages

contentMode 일부 예시
이미지 프레임 : (x: 20, y: 70, width: 80, height: 120)
이미지 원본 : 
.scaleAspectFit
: 비율을 고정한 채로 프레임을 최대한 채움. (뷰에 남는 부분 있음)
.scaleAspectFill
: 비율을 고정한 채로 뷰를 가득 채움 (이미지 잘릴 수 있음)
.scaleToFill
: 비율을 변경하여 프레임을 가득 채움
.left
: 원본 크기 유지, 위치는 왼쪽에 맞춤

 

[더보기] 이미지 가져오는 법

더보기

참고: https://developer.apple.com/documentation/xcode/adding-images-to-your-xcode-project

1. Project navigator > Assets 로 이동

2. finder에서 이미지 파일을 outline view로 드래그 (+ 더블클릭하여 이미지 이름 변경)

3. 코드에서 이미지를 불러오기

// SwiftUI
let image = Image("ImageName")

// UIKit
let image = UIImage(named: "ImageName")

// AppKit
let image = NSImage(named: "ImageName")

🔹 UITextField

- 정의 : 사용자로부터 텍스트를 입력받기 위해 사용되는 UI 요소 (User interection ⭕️ )

- 주요 속성 : text, placeholder, keyboardType, isSecureTextEntry, delegate, returnKeyType

4가지 borderStyle
.bezel .line .none .roundedRect

 

🔹 UIButton

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

- 주요 속성 : titleLabel, setImage(_:for:), setTitle(_:for:), addTarget(_:action:for:), isEnabled

 

 

결과

 

 

[더보기] .addTarget

더보기

출처 : https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

 

Parameters

target

The target object—that is, the object whose action method is called. If you specify nil, UIKit searches the responder chain for an object that responds to the specified action message and delivers the message to that object.

 

action

A selector identifying the action method to be called. You may specify a selector whose signature matches any of the signatures in Listing 1. This parameter must not be nil.

 

controlEvents

A bitmask specifying the control-specific events for which the action method is called. Always specify at least one constant. For a list of possible constants, see UIControl.Event.

 

Discussion

You may call this method multiple times to configure multiple targets and actions for the control. It is also safe to call this method multiple times with the same values for the target and action parameters. The control maintains a list of its attached targets and actions along with the events each supports.

The control does not retain the object in the target parameter. It is your responsibility to maintain a strong reference to the target object while it is attached to a control.

Specifying a value of 0 for the controlEvents parameter does not prevent events from being sent to a previously registered target and action method. To stop the delivery of events, always call the removeTarget(_:action:for:) method.

 


🔹 UISwitch

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

- 주요 속성 : isOn, onTintColor, thumbThintColor, addTarget(_:action:for:)

On Off

 


🔹 UISlider

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

- 예시 : 볼륨 조절 슬라이더

- 주요 속성 : value, minimumValue, maximumValue, minimumTrackTinkColor, maximumTrackTinkColor, thumbTinkColor, addTarget(_:action:for)

 

초기값 설정은 min & max Value 설정 이후에!!
이후에 하는 경우 이전에 하는 경우

 


🔹 UISegmentedControl

- 정의 : 여러 개의 세그먼트로 구성된 컨트롤로, 각 세그먼트를 선택하여 원하는 옵션을 선택할 수 있는 UI 요소 (User interection ⭕️ )

- 예시 : 탭 바, 네비게이션 바

- 주요 속성 : selectedSegmentIndex, numberOfSegments, tintColor, isMomentary

 

isMomentary : 선택 표시를 유지할지 여부
false
: 선택 표시 유지함
true
: 선택 표시 유지 안함(momentary)

 


🔹 UIScrollView

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

- 주요 속성 : contentSize, contentOffset, contentInset, isScrollEnabled, isPagingEnabled, bounces

 

페이지 기능
isPagingEnabled = false isPagingEnabled = true

 

 


🔹 UIPickerView

- 정의 : 사용자가 여러 개의 옵션 중 하나를 선택할 수 있는 회전 가능한 휠 형식의 UI 요소

- 주요 속성 : dataSource, delegate, numberOfComponents, selectedRow(inComponent:)

 

// class에서 UIViewController에 더해 UIPickerViewDelegate, UIPickerViewDataSource를 추가로 상속

// 코드

 

결과
UIView
프린트된 것

 


🔹 UITableView

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

- 주요 속성 : 

dataSource: UITableView의 데이터를 제공하는 객체를 설정합니다.
delegate: UITableView의 이벤트를 처리하는 객체를 설정합니다.
rowHeight: 각 행의 높이를 설정합니다.
separatorStyle: 행 간 구분선의 스타일을 설정합니다.
separatorColor: 행 간 구분선의 색상을 설정합니다.
allowsSelection: 테이블 뷰에서 행 선택을 허용할지 여부를 설정합니다.

 

// class에서 UIViewController에 더해 UITableViewDelegate, UITableViewDataSource를 추가로 상속

// 코드

tableView.deselectRow(at:animated:) : 터치 해제 시 음영 제거하는 기능
deselect O deselect X
 

 


 

🔹 UICollectionView

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

- 예시 : 사진첩

- 주요 속성 : dataSource, delegate, collectionViewLayout, allowsSelection, allowsMultipleSelection

 

// class에서 UIViewController에 더해 UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout를 추가로 상속

 

// 코드

 

결과