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

Cách vô hiệu hóa (disable) UIScrollView bằng code trong iOS

UIScrollView là một trong những component phức tạp nhất iOS. Để vô hiệu hóa scroll, chỉ cần set property isScrollEnabled = false.

Code cơ bản

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Vô hiệu hóa scroll
        scrollView.isScrollEnabled = false
    }
}

Các trường hợp thường gặp

1. Bật/tắt động theo điều kiện

// Ví dụ: Chỉ cho scroll khi content lớn hơn màn hình
func updateScrollEnabled() {
    let contentHeight = scrollView.contentSize.height
    let viewHeight = scrollView.frame.height
    scrollView.isScrollEnabled = contentHeight > viewHeight
}

// Gọi trong viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    updateScrollEnabled()
}

2. Vô hiệu hóa tạm thời (ví dụ khi keyboard hiện)


// Khi keyboard xuất hiện
scrollView.isScrollEnabled = false

// Khi keyboard ẩn
scrollView.isScrollEnabled = true

3. Vô hiệu hóa chỉ một chiều

// Chỉ scroll dọc
scrollView.alwaysBounceHorizontal = false
scrollView.alwaysBounceVertical = true

// Chỉ scroll ngang
scrollView.alwaysBounceHorizontal = true
scrollView.alwaysBounceVertical = false

4. Vô hiệu hóa scroll nhưng vẫn cho phép bounce (pull to refresh)


scrollView.isScrollEnabled = false
scrollView.alwaysBounceVertical = true // Vẫn pull được để refresh
// Cần xử lý gesture recognizer tùy chỉnh

Lưu ý quan trọng

  • isScrollEnabled = false cũng vô hiệu hóa zoom (nếu có)
  • ContentOffset vẫn có thể set bằng code: scrollView.setContentOffset(CGPoint(x: 0, y: 100), animated: true)
  • Nếu dùng UITableView hoặc UICollectionView (kế thừa từ ScrollView), property này cũng áp dụng
  • Để chặn scroll nhưng vẫn nhận touch: subclass ScrollView override touchesShouldBegin

Extension tiện ích


extension UIScrollView {
    func disableScroll() {
        isScrollEnabled = false
    }
    
    func enableScroll() {
        isScrollEnabled = true
    }
    
    var isScrollable: Bool {
        return contentSize.height > frame.height || contentSize.width > frame.width
    }
}