Computer >> Máy Tính >  >> Lập trình >> IOS

Làm thế nào để sử dụng UICollectionView trong Swift?


Để sử dụng chế độ xem bộ sưu tập nhanh chóng, trước tiên, chúng ta cần tạo Chế độ xem bộ sưu tập. Chúng ta có thể kéo và thả nó vào bảng phân cảnh hoặc có thể tạo nó theo lập trình. Sau đó, chúng ta cần xác nhận lớp của mình với UICollectionViewDataSource và UICollectionViewDelegate. Ngoài ra, nếu chúng ta cần bố cục và kích thước ô tùy chỉnh, chúng ta cần xác nhận nó với UICollectionViewDelegateFlowLayout.

Hãy xem bước bắt buộc để tạo bộ sưu tập Chế độ xem theo chương trình.

func initCollection() {
   let layout = UICollectionViewFlowLayout()
   layout.itemSize = CGSize(width: 50, height: 50)
   let collection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)
   collection.dataSource = self
   collection.delegate = self
   collection.backgroundColor = colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
   collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
   self.view.addSubview(collection)
}

Chúng ta cần gọi hàm trên trong phương thức ViewDidLoad () của chúng ta. Cho dù chúng tôi tạo bộ sưu tập theo chương trình hay bằng bảng phân cảnh, chúng tôi cần phân bổ nguồn dữ liệu và ủy quyền cung cấp dữ liệu cho bảng và quan sát các hành động của nó tương ứng.

Bây giờ, chúng ta cần cho biết bộ sưu tập, nó phải có bao nhiêu phần -

func numberOfSections(in collectionView: UICollectionView) -> Int {
   return 1
}

Sau đó, chúng ta cần cho biết nó sẽ có bao nhiêu mục và dữ liệu nào nên có trong các ô.

func collectionView(_ collection: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return 7
}
func collectionView(_ collection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
   cell.layer.backgroundColor = colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)
   return cell
}

Tùy chọn, chúng tôi có thể cung cấp cho nó kích thước khác nhau theo yêu cầu.

func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
   let size = CGSize(width: 200, height: 50)
   return size
}

Khi chúng tôi chạy mã trên trên một thiết bị, đây là kết quả được tạo ra.

Làm thế nào để sử dụng UICollectionView trong Swift?