在Swift中有多个子类实例

时间:2016-02-02 18:30:33

标签: swift

我已经将UICollectionViewCell子类化为UIImageView。此图像视图连接到故事板上的图像视图控件。这是子类:

class ProfilesCell: UICollectionViewCell {
    @IBOutlet weak var ProfileImage: UIImageView!

    func setCell(item:Profile) {
        ProfileImage.image = UIImage(named: item.profileThumb)
        ProfileImage.layer.borderWidth = 0.5
        ProfileImage.layer.borderColor = UIColor.grayColor().CGColor
    }
}

我已经创建了它的一个实例并且工作正常,但是另一个实例呢?如何在不将UICollectionViewCell重新连接到另一个控件的情况下将其选为另一个ProfileImage的自定义类?

或者我应该将IBOutlet首先连接到UIImageView吗?

故事板: enter image description here

2 个答案:

答案 0 :(得分:1)

  

此图像视图[来自单元格]连接到故事板上的图像视图控件。

我假设你在谈论UICollectionViewCell 原型。在这种情况下,您在故事板中操作的对象不是 集合视图单元格,它是您{{1}中所有图像视图单元格的原型 }}

  

我已经创建了它的一个实例并且工作正常,但是另一个实例呢?

这正是Swift设计师想到的场景,所以一切都应该按照你期望的方式工作。当你调用UIImageView方法时,Cocoa会为你实例化单元格,"连线"您的dequeueReusableCellWithReuseIdentifier:ProfileImage出口,并为您提供可供使用的单元格。

答案 1 :(得分:1)

如果要跨多个UICollectionView使用UICollectionViewCell,则应在单独的.xib中创建UICollectionViewCell。在这种情况下,您将拥有ProfileCell.xib和ProfileCell.swift。在.xib文件中,将UICollectionViewCell的实例拖到屏幕上,并将其设置为您在CollectionView上作为原型单元格的方式。

UICollectionViewCell on xib

然后,您需要使用收集视图注册单元格。

    //set this up in viewDidLoad
    let nib = UINib(nibName: "ProfileCell", bundle: nil)
    self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "ProfileCell")

然后在cellForItemAtIndexPath中以正常方式引用单元格

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    cell =    self.collectionView?.dequeueReusableCellWithReuseIdentifier("ProfileCell, forIndexPath: indexPath) as! ProfileCell
    cell.setCell()
    return cell
 }
相关问题