在.xib中的UICollectionViewCell中使用IBOutlet时,NSUnknownKeyException

时间:2018-07-24 12:12:00

标签: ios swift xcode xib

我一直在尝试使用IBOutlet从标签中添加标签到自定义UICollectionViewCell类,该类打算用作我拥有的UICollectionView的单元格在另一个xib中,但是当我添加插座时,我在创建的标签参考上看到一个NSUnknownKeyException,没有插座参考,单元的内容将正确加载,但是我希望能够操纵单元中的标签

这是我的父母xib课堂上的内容:

class Calendar : UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
   let nibName: String = "Calendar"
   let calendarDayNibName: String = "CalendarDay"
   let calendarReusableCellName: String = "CalendarCell"
   let calendarDaysLimit: Int = 35
   var contentView: UIView?

   @IBOutlet var sundayLabel: UILabel!
   @IBOutlet var mondayLabel: UILabel!
   @IBOutlet var tuesdayLabel: UILabel!
   @IBOutlet var wednesdayLabel: UILabel!
   @IBOutlet var thursdayLabel: UILabel!
   @IBOutlet var fridayLabel: UILabel!
   @IBOutlet var saturdayLabel: UILabel!
   @IBOutlet var calendarDays: UICollectionView!

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

       guard let view = self.loadViewFromNib() else { return }
       view.frame = self.bounds
       self.addSubview(view)
       contentView = view
       contentView?.isUserInteractionEnabled = true
   }

   override func awakeFromNib()
   {
       super.awakeFromNib()

       calendarDays.register(UINib(nibName: calendarDayNibName, bundle: nil), forCellWithReuseIdentifier:calendarReusableCellName)
       calendarDays.dataSource = self
   }

   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
   {
       return calendarDaysLimit;
   }

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
   {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: calendarReusableCellName, for: indexPath)
       configureCell(cell: cell)
       return cell
   }

   private func configureCell(cell: UICollectionViewCell)
   {
       //does nothing right now, placeholder for if configuring cell on
       //collection view load
   }

   private func loadViewFromNib() -> UIView? {
       let bundle = Bundle(for: type(of: self))
       let nib = UINib(nibName: nibName, bundle: bundle)
       self.isUserInteractionEnabled = true
       return nib.instantiate(withOwner: self, options: nil).first as? UIView
   }

   public func loadCalendarDays(month: Int)
   {
       //todo: write day loading logic here
   }
}

这是子xib类(UICollectionViewCell):

class CalendarDay: UICollectionViewCell
{
   @IBOutlet weak var dayLabel: UILabel!  
}

如果可以帮助查看以下内容,这是我的总体项目:https://github.com/CharlemagneVI/practice-calendar

1 个答案:

答案 0 :(得分:1)

您将类和IBOutlet连接设置为错误...好吧,不是很正确...

CalendarDay.xib中,File's Owner的类应为默认的NSObject

enter image description here

,它应该具有任何连接:

enter image description here

单元格对象本身的类应为CalendarDay

enter image description here

是您建立联系的地方:

enter image description here

enter image description here

应该这样做:)