Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách tạo UITextView có thể cuộn (scrollable) trên iOS App

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

  1. Kéo Text View từ Object Library vào View.
  2. Attribute Inspector: Tích Scrolling Enabled, User Interaction Enabled.
  3. Thêm constraints: Top, Leading, Trailing, Bottom (hoặc Height cố định).
  4. Nội dung text > chiều cao khung > tự động cuộn.

Cách tạo UITextView có thể cuộn (scrollable) trên iOS App

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ả

Cách tạo UITextView có thể cuộn (scrollable) trên iOS App

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 UIToolbar làm inputAccessoryView vớ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)