UICollectionView इम्प्लीमेंटेशन
Swift में कलेक्शन व्यू का उपयोग करने के लिए, पहले हमें एक कलेक्शन व्यू बनाने की आवश्यकता है। हम या तो इसे स्टोरीबोर्ड पर ड्रैग और ड्रॉप कर सकते हैं, या इसे प्रोग्रामेटिकली बना सकते हैं। उसके बाद, हमें अपनी क्लास को UICollectionViewDataSource और UICollectionViewDelegate के अनुरूप बनाने की आवश्यकता है। अगर हमें कस्टम सेल साइज और लेआउट की आवश्यकता है, तो हमें इसे UICollectionViewDelegateFlowLayout के अनुरूप बनाने की भी आवश्यकता है।
प्रोग्रामेटिकली कलेक्शन व्यू बनाने के लिए आवश्यक चरण:
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 = UIColor.green
collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
self.view.addSubview(collection)
}
हमें उपरोक्त फंक्शन को अपने viewDidLoad() मेथड में कॉल करने की आवश्यकता है। चाहे हम कलेक्शन प्रोग्रामेटिकली बनाएं या स्टोरीबोर्ड के साथ, हमें डेटा सोर्स और डेलीगेट आवंटित करने की आवश्यकता है ताकि टेबल को डेटा दिया जा सके और उसके एक्शन का अवलोकन किया जा सके।
अब, हमें कलेक्शन को बताना होगा कि इसमें कितने सेक्शन होने चाहिए:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
उसके बाद, हमें यह बताना होगा कि इसमें कितने आइटम होंगे, और सेल्स में क्या डेटा मौजूद होना चाहिए।
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 = UIColor.red.cgColor
return cell
}
वैकल्पिक रूप से हम इसे आवश्यकता के अनुसार अलग आकार दे सकते हैं।
func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width: 200, height: 50)
return size
}
जब हम उपरोक्त कोड को डिवाइस पर चलाते हैं, तो यह परिणाम उत्पन्न होता है:
