我在UIViewcontroller
的CollectionView中遇到問題。 我從JSON中獲取數據,並且在特殊情況下單元格似乎沒有被正確重用,而且我認爲我設置CollectionView的方式有些問題。Swift CollectionView可重複使用的單元格註冊
一個概述:
我MyCollectionViewCell.swift
:
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var bottomLabel: UILabel!
@IBOutlet weak var topLabel: UILabel!
}
正如你可以看到我在小區的兩個標籤。我的viewController的 及零部件:
import UIKit
private let reuseIdentifier = "colcel"
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
//collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
//SOME JSON PARSING HAPPENS HERE
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let colcel = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyCollectionViewCell
colcel.contentView.layer.cornerRadius = 5.0
colcel.layer.shadowColor = UIColor.darkGray.cgColor
colcel.layer.shadowOffset = CGSize(width: 12, height: 4.0)
colcel.layer.shadowRadius = 12.0
colcel.layer.masksToBounds = false
return colcel
}
}
現在,當我嘗試使用,例如:
colcel.topLabel.text = "someText"
我得到:
fatal error: unexpectedly found nil while unwrapping an Optional value
當我刪除了collectionview.register
在它的工作原理viewDidLoad()
。 現在的問題是我的register
行動沒有必要或者它是錯的?
//編輯。
我的手機重新排序:
在viewDidLoad()
是這樣的:
//Long Pressure for reordering
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongGesture))
self.collectionView.addGestureRecognizer(longPressGesture)
這是相應的功能:
func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
,我有這樣的功能:
func collectionView(_ collectionView: UICollectionView,
moveItemAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath)
{
// Update data model to reflect the change
let temp = devArray[sourceIndexPath.row]
devArray[sourceIndexPath.row] = devArray[destinationIndexPath.row]
devArray[destinationIndexPath.row] = temp
}
當我運行
self.collectionView.reloadData()
有時位置跳
您確定您的topLabel已正確連接爲iboutlet嗎? – MaksTheAwesome
檢查「topLabel」插座是否連接正確。 – PGDev
我確定它是,當我刪除註冊它的作品,我看到故事板中的連接 – theslash