Post

UIKit - UITextView 동적 높이 조정하기

UIKit - UITextView 동적 높이 조정하기

UITextView에 높이를 동적으로 조정하기 위해선 아래와 같이 Delegate 메서드를 통해 구현할 수 있음.

TodoAddViewController.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// MARK: - TextView Delegate
extension TodoAddViewController: UITextViewDelegate{

    ...
    
    func textViewDidChange(_ textView: UITextView) {
        let size = CGSize(width: view.frame.width, height: .infinity)

        // textview의 적합한 사이즈로 계산
        let estimateSize = textView.sizeThatFits(size)
        
        textView.constraints.forEach { constraint in
            
            guard estimateSize.height > 150 && estimateSize.height < 250 else { return }
            
            if(constraint.firstAttribute == .height){
              // height constant 적용
                constraint.constant = estimateSize.height
            }
        }
    }
}

TodoAddView.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import UIKit

class TodoAddView: UIView {

    ...

    // MARK: - 할일 세부 사항(또는 메모) 텍스트 뷰
    let todoDescriptionTextView: UITextView = {
        let textView = UITextView()
        
        ....
        
        // isScrollEnabled false 설정
        textView.isScrollEnabled = false
        
        ....
        
        return textView
    }()

    ...
}

결과

image

Reference

This post is licensed under CC BY 4.0 by the author.