为什么UICollectionViewCell的出口是零?

Ján*_*nos 139 interface-builder ios uicollectionviewcell swift ios8

我在Interface Builder中创建了一个自定义UICollectionViewCell,将它绑定到类上,然后当我想使用并将字符串设置为字符串上的标签时,tha label的值为nil.

override func viewDidLoad() {
    super.viewDidLoad()

    // Register cell classes
    self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls")
}

override func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {

    var cell: LeftMenuCollectionViewCell
    cell = collectionView.dequeueReusableCellWithReuseIdentifier("ls", forIndexPath: indexPath) as LeftMenuCollectionViewCell
    println(cell.label) // <- this is nil, why??
    cell.label.text = "asd"

    return cell
}
Run Code Online (Sandbox Code Playgroud)

和子类细胞:

class LeftMenuCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
}
Run Code Online (Sandbox Code Playgroud)

Ján*_*nos 292

self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls")再次打电话.如果您使用的是故事板,则不希望将其称为"故事板".它将覆盖故事板中的内容.

如果您仍然有问题请检查是否reuseIdentifier相同dequeueReusableCellWithReuseIdentifier ,并storyboard.

  • 谢谢!花了一个多小时才使用自定义单元格. (17认同)
  • **如果您使用故事板,则不想打电话给它.它将覆盖你的故事板中的内容.**< - 这个真的帮帮我了 (12认同)
  • GAH,在UICollectionViewController模板中有一个可怕的东西!!!!! 谢谢,Janos. (5认同)
  • 哇谢谢!永远不会自己找到这个! (2认同)

能蟹仔*_*能蟹仔 52

只需删除此行:

self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls")
Run Code Online (Sandbox Code Playgroud)

  • 我不明白为什么这被投了票.这是我的问题的答案. (3认同)
  • 猜猜它被投票了,因为这个问题在2014年8月本身得到了解答......而这个答案只是在几个月之后再次在这里复制了答案. (3认同)

Vin*_*eth 44

如果您使用的是xib,请确保已将此行代码添加到viewdidload中.

目标C:

[self.collectionView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellWithReuseIdentifier:@"MyCellIdentifier"];
Run Code Online (Sandbox Code Playgroud)

迅速:

collectionView.register(UINib(nibName:"MyCell", bundle: nil), forCellWithReuseIdentifier:"MyCellIdentifier")
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚注册了笔尖,它解决了我的问题. (3认同)

Mic*_*ael 16

要注册那个笔尖的家伙!

collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "CustomCellId")
Run Code Online (Sandbox Code Playgroud)


Ser*_*gio 10

看起来有两种注册方式,第一种我用错了。我有一个自定义的 xib 视图,所以注册了第二个选项,我们有数据!

1:

collectionView?.register(YourItemClassName.self, forCellWithReuseIdentifier: "yourIdentifier") 
Run Code Online (Sandbox Code Playgroud)

2:

collectionView?.register(UINib(nibName: "YourItemClassName", bundle: nil), forCellWithReuseIdentifier: "yourIdentifier")
Run Code Online (Sandbox Code Playgroud)