在Storyboard中使用UICollectionViewCells时,我目前总是遇到错误。没有其他控件显示此行为。我该怎样摆脱它们?
这是其中一个受影响的CollectionViewCells的样子:
这是我定义它的方式:
以下是CategoryCollectionCell
import UIKit
import Foundation
@IBDesignable class CategoryCollectionCell : UICollectionViewCell {
@IBOutlet private weak var imageView: UIImageView!
@IBOutlet private weak var label: UILabel!
internal var id : Int?
override var highlighted : Bool {
didSet {
label.textColor = highlighted ? UIColor.greenColor() : UIColor.whiteColor()
}
}
@IBInspectable var text : String? {
get { return label.text }
set(value) { label.text = value }
}
@IBInspectable var image : UIImage? {
get { return imageView.image }
set(value) { imageView.image = value }
}
}
这是CollectionViewController的代码:
extension CategoryViewController : UICollectionViewController {
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = self.collectionView?.dequeueReusableCellWithReuseIdentifier(kReuseCellIdentifier, forIndexPath: indexPath)
var categoryCollectionCell = cell as? CategoryCollectionCell
if categoryCollectionCell == nil {
categoryCollectionCell = CategoryCollectionCell()
}
let data = getDataForIndexPath(indexPath)
if data != nil {
categoryCollectionCell?.id = data!.id
categoryCollectionCell!.text = data!.category
categoryCollectionCell!.image = data!.image
}
return categoryCollectionCell!
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
}
extension CategoryViewController : UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
return CGSize()
}
let width = CGRectGetWidth(collectionView.bounds)
let padding = flowLayout.sectionInset.left + flowLayout.sectionInset.right
let itemSpacing = flowLayout.minimumInteritemSpacing
let size = (width - padding - itemSpacing) / 2
return CGSize(width: size, height: size)
}
}
答案 0 :(得分:1)
确定。我发现XCode显示的错误与实际问题无关。
目录/Users/{Username}/Library/Logs/DiagnosticReports
应包含名称如下的文件:IBDesignablesAgentCocoaTouch[...].crash
在他们内部,我发现堆栈跟踪导致我遇到了真正的问题:
问题出现在自定义UITableViewCell
的代码中,而不是UICollectionViewCell
class FooTableCell : UITableViewCell {
@IBOutlet private weak var checkmarkImageView: UIImageView!
override internal var selected : Bool {
didSet {
checkmarkImageView.hidden = !selected
}
}
}
使用设计器时checkmarkImageView
为nil
。因此,Cocoa Storyboard Agent崩溃了。
我通过添加一个保护声明来修复它:
class FooTableCell : UITableViewCell {
@IBOutlet private weak var checkmarkImageView: UIImageView!
override internal var selected : Bool {
didSet {
guard let imageView = checkmarkImageView else {
return
}
imageView.hidden = !selected
}
}
}