[英]UICollectionView queries with dequeuing
我有一個UICollectionView,使網格。 組成網格的每個單元都有一個UIImage(在IB中創建)。
我正在使用可重復使用的單元格以減少請求。 如何使用此單元格和UIImage? 在它消失之前是否有某種方式將其存儲在數組中? 我已經創建了標簽,但是這樣做是否有幫助? 如果我手動創建每個單元,則控制器中將有大約100個@IBOutlets! 這是我的代碼以顯示單元格。
任何想法都會很棒。 我試圖將UIImage放入單元格中,因此我可以將其隱藏並在單元出隊之前對其進行命名。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("LetterCell", forIndexPath: indexPath) as UICollectionViewCell
cell.tag = indexPath.row
return cell
}
圖像占用大量內存。 結果,您通常不希望一種架構要求您一次將所有圖像(或更糟糕的是,單元格)保存在內存中。 您希望您的集合視圖單元格可以重用,並且您希望以一種及時的方式(也就是“惰性”圖像加載)從持久性存儲中檢索圖像。
為了最大程度地減少應用程序的內存占用,因此模型通常只包含最少量的信息,例如僅引用這些圖像(例如文件名)。 僅在UI真正需要時才加載圖像。
例如,假設圖像是設備的“應用程序支持”文件夾中的文件,那么您可能具有文件名數組(在下面的示例中稱為imageNames
),並且您可能會執行以下操作:
var imageNames = [String]() // this is populated elsewhere, perhaps `viewDidLoad`
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCell
let imageURL = try! FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent(imageNames[indexPath.item])
cell.imageView.image = UIImage(contentsOfFile: imageURL.path)
return cell
}
如果您確實想將這些圖像保存在內存中(例如,為了獲得更平滑的響應時間),則可以使用NSCache
,但是請確保在收到內存壓力時此緩存清空。 例如:
var imageCache = ImageCache()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCell
let imageName = imageNames[indexPath.item]
if let image = imageCache[imageName] {
cell.imageView.image = image
} else {
let imageURL = try! FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent(imageName)
let image = UIImage(contentsOfFile: imageURL.path)
imageCache[imageName] = image
cell.imageView.image = image
}
return cell
}
哪里
class ImageCache: NSCache<NSString, UIImage> {
var observer: NSObjectProtocol?
override init() {
super.init()
// empty queue upon memory pressure
observer = NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main) { [unowned self] notification in
self.removeAllObjects()
}
}
deinit {
NotificationCenter.default.removeObserver(observer!)
}
subscript(key: String) -> UIImage? {
get { return object(forKey: key as NSString) }
set { setValue(newValue, forKey: key) }
}
}
人們可能還會考慮其他優化。 例如,如果這些圖像很大,則可能要確保您正在加載的圖像視圖中的圖像大小已調整為最適合集合視圖單元格的大小。 但是希望這可以說明在UICollectionView
處理圖像時的一些基本概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.