Class 扩展 UICollectionView 的初始化程序(Swift 3.2)

Initializers of a Class Extending UICollectionView (Swift 3.2)

我正在 Swift 3.2 中编码。我有一个名为 EventCollectionView 的 class,它扩展了 UICollectionView。这个 class 的一个实例是 'event',我想用三个 UIImage 初始化它,这些图像显示活动照片、活动信息和活动门票。

但是,当我尝试在自定义初始化程序中调用 super.init() 时,我收到一条错误消息,指出 'Must call a designated initializer of the superclass UICollectionView.' 我已尝试实施 super.init(frame:CGRect) 但这似乎也不起作用.

下面是我EventCollectionViewclass的第一部分。

var eventPhoto: UIImage?
var eventInfo: UIImage?
var eventTickets: UIImage?

//Initializers
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

init?(eventPhoto: UIImage?, eventInfo: UIImage?, eventTickets: UIImage?) {
    super.init()       //Where the error occurs
    self.eventPhoto = eventPhoto
    self.eventInfo = eventInfo
    self.eventTickets = eventTickets

如有任何见解,我们将不胜感激。

Apple developer documents 看来,合适的 init 方法签名应该是:init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout)。例如,您的 init 方法可以变成:

init?(eventPhoto: UIImage?, eventInfo: UIImage?, eventTickets: UIImage?) {

    let flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    let collectionViewFrame:CGRect = CGRect(x: 0, y: 0, width: 200, height: 200)

    super.init(frame: collectionViewFrame, collectionViewLayout: flowLayout)  
    ...
}

所以如果你想通过故事板初始化这样的 EventCollectionView 你应该以另一种方式注入这些参数,比如:

class EventCollectionView:UICollectionView {
  var eventPhoto: UIImage?
  var eventInfo: UIImage?
  var eventTickets: UIImage?

  func setup(eventPhoto: UIImage?, eventInfo: UIImage?, eventTickets: UIImage?) {
    self.eventPhoto = eventPhoto
    self.eventInfo = eventInfo
    self.eventTickets = eventTickets
  }
}

那么你应该在初始化后随时调用 setup 例如:

import UIKit

class YourViewController: UIViewController {
  @IBOutlet var collectionView:EventCollectionView!

  override func viewDidLoad() {
    super.viewDidLoad()

    // setup whatever here:
    let photo:UIImage? = nil
    let info:UIImage? = nil
    let tickets:UIImage? = nil
    collectionView.setup(eventPhoto: photo, eventInfo: info, eventTickets: tickets)
  }
}