在Swift中给自定义的UICollectionViewCell标签插座(Label Outlet)造成Optional.None崩溃问题。

10
我有一个collectionViewController,想要展示一堆带有标签的自定义UICollectionViewCells。不幸的是,每当我试图访问自定义UICollectionViewCell的标签时,会引起崩溃,并显示以下信息:
控制台
"fatal error: Can't unwrap Optional.None"
窗口
"Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)"
我尝试这样访问标签:
cell.name.text = names[indexPath!.item]

也许这是因为我的插座标签为空?但是寻找答案时,没有任何有效的方法,而且由于我不确定问题所在,因此在我的代码中添加?/!并不能真正帮助解决问题。

MyCustomUICollectionViewController

class ScrambledTextCollectionViewController: UICollectionViewController {

    var names: String[] = ["Anna", "Alex", "Brian", "Jack"]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView.registerClass(MyCustomCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView?) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int {
        return names.count
    }

    override func collectionView(collectionView: UICollectionView?, cellForItemAtIndexPath indexPath: NSIndexPath?) -> UICollectionViewCell? {
        var cell = collectionView?.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as MyCustomCollectionViewCell

        cell.name.text = names[indexPath!.item]

        return cell
    }
}

MyCustomCollectionViewCell

class MyCustomCollectionViewCell: UICollectionViewCell {

    @IBOutlet var name: UILabel
    init(frame: CGRect) {
        super.init(frame: frame)                
    }
}

1
也许我有点傻,但是你没有在viewDidLoad的范围之外定义var names。你应该在整个对象的范围内定义变量var names,而不仅仅是在viewDidLoad中。 - Fogmeister
尝试将感叹号替换为问号标记names[indexPath?.item]。 - Greg
我不相信这会解决我的问题,即使我直接设置标签cell.name.text =“Hello”,它也会崩溃。让我困惑的是,我以类似的方式使用自定义UITableViewCell创建了一个UITableView,但没有出现问题。 - William Robinson
1
我遇到了同样的问题,我的标签和图像视图从自定义集合单元中返回为空。我已经检查了连接和类名是否正确,但没有运气。有没有任何解决方案? - Arnlee Vizcayno
1
这很简单,但我也无法让它工作。Swift正在给我带来麻烦! - DogCoffee
显示剩余5条评论
1个回答

11

在这里找到了答案:这里

删除self.collectionView.registerClass(MyCustomCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

详细原因请阅读链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接