sizeToFit()
Resizes and moves the receiver view so it just encloses its subviews. Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs.
- 안에 있는 element(label의 경우, 글자의 intrinsic size)에 따라서 view의 사이즈가 알아서 조절되는 것!
😎 예시를 통해서 알아보자. 아래는 textfield의 extension을 통하여 keyboard위에 toolbar를 추가하는 코드이다.
- 아래의 코드에서 toolbar는 사이즈를 따로 설정하지 않았다. 그 상태로만 AccessoryView로 넣었으면 화면에서 toolbar가 보이지 않았을 것이다. → 사이즈가 설정되지 않았기에!
- sizeToFit()를 통하여 toolbar의 사이즈를 toolbar안의 UIBarButtonItem 사이즈에 맞게 설정할 수 있다.
‼️ 그렇다면 toolbar의 사이즈를 설정해 줄 수 있을까? ⇒ 현재 코드에서 toolbar 사이즈를 설정해주어도 toolbar의 사이즈는 변경되지 않는다! 단, 사이즈를 설정해 줄 경우(아무 사이즈나 설정해줘도 된다), 따로 sizeToFit() 함수를 호출해주지 않아도 된다.
func addDoneButtonToKeyboard(doneAction: Selector?) {
let doneToolbar: UIToolbar = UIToolbar()
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: nil, action: doneAction)
doneToolbar.setItems([flexSpace, done], animated: false)
// toolbar의 사이즈를 조정해준다!
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
+ToolBar 설정해주는 방법
// Toolbar 생성하기
let doneToolbar: UIToolbar = UIToolbar()
doneToolbar.barStyle = .default
// 빈 공간 => flexSpace
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: nil, action: doneAction)
// setItems를 통해서 toolbar에 아이템 넣어주기
doneToolbar.setItems([flexSpace, done], animated: false)
// toolbar의 사이즈를 조정해준다!
doneToolbar.sizeToFit()
'iOS' 카테고리의 다른 글
[iOS] 의존성 관리 도구(Package Manager) (0) | 2023.02.21 |
---|---|
[iOS] TableView에서 Swipe해서 Delete하기 (0) | 2023.02.09 |
[iOS] Target-Action Pattern (0) | 2023.02.06 |
[iOS] UIResponder (0) | 2023.02.06 |
[iOS] CGPoint, CGSize, CGRect (0) | 2023.02.06 |