UITextView kế thừa từ UIScrollView, nên mặc định đã có khả năng cuộn nếu nội dung lớn hơn khung hiển thị. Chỉ cần bật isScrollEnabled = true (mặc định true) và đảm bảo text đủ dài.
Cách 1: Storyboard
- Kéo Text View từ Object Library vào View.
- Attribute Inspector: Tích Scrolling Enabled, User Interaction Enabled.
- Thêm constraints: Top, Leading, Trailing, Bottom (hoặc Height cố định).
- Nội dung text > chiều cao khung > tự động cuộn.

Cách 2: Code (Programmatically)
let textView = UITextView()
textView.isScrollEnabled = true
textView.isUserInteractionEnabled = true
textView.frame = CGRect(x: 10, y: 10, width: view.frame.width - 20, height: 100)
textView.font = .systemFont(ofSize: 16)
textView.text = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
"""
view.addSubview(textView)
Kết quả

Lưu ý quan trọng
- Nếu không muốn cuộn (text view tự co giãn theo nội dung):
isScrollEnabled = false+ Auto Layout constraints (content size drive height). textContainerInsetđể set padding bên trong text view (mặc định 8pt).textContainer.lineFragmentPadding= 0 để bỏ padding trái/phải mặc định.- Keyboard: Thêm
UIToolbarlàminputAccessoryViewvới nút Done để dismiss keyboard. - Delegate
UITextViewDelegateđể bắt sự kiện text change, selection change.
Auto-sizing TextView (Dynamic Height)
// Tắt scroll, dùng Auto Layout
textView.isScrollEnabled = false
// Constraints: top, leading, trailing, bottom (to superview)
// TextView sẽ tự mở rộng chiều cao theo nội dung
// Cần set contentCompressionResistancePriority vertical cao
textView.setContentCompressionResistancePriority(.required, for: .vertical)