案例:
我在UIView中使用了一个集合视图,我已将它作为名为'partsCollectionView'
的插座连接起来。我已为该单元格创建了一个标识为'cell'
且自定义类'SelectionCollectionViewCell'
的单元格。在单元格中,我有一个名为“cellTitle'”的标签。
错误: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
我在设置' cellForItemAt
'内的标签值时遇到错误?方法
以下是相关观点:
单元格描述,
和,集合视图说明
Cell Class是:
import UIKit
class SelectionCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cellTitle: UILabel!
}
我将使用集合视图的类是:
import UIKit
private let reuseIdentifier = "cell"
let array = ["small","Big","Medium","Very big","Toooo big String","small"]
class SelectionCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var partsCollectionView: UICollectionView!
@IBOutlet weak var instructionsView: UITextView!
@IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.partsCollectionView.register(SelectionCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = partsCollectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SelectionCollectionViewCell
cell.layer.cornerRadius = 10
cell.clipsToBounds = true
cell.cellTitle.text = array[indexPath.row]
cell.layer.borderColor = #colorLiteral(red: 0.07843137255, green: 0.6862745098, blue: 0.9529411765, alpha: 0.6819349315)
cell.layer.borderWidth = 2
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let name = array[indexPath.row]
let attributedName = NSAttributedString(string: name)
let width = attributedName.widthWithConstrainedHeight(height: 20.0)
return CGSize(width: width + 40, height: 30.0)
}
}
extension NSAttributedString {
func widthWithConstrainedHeight(height: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
return boundingBox.width
}
}
更新:如果我跳过设置标题文字,这就是它的样子。标题将出现在那些圆形框内。
答案 0 :(得分:3)
从viewDidLoad
删除此行。
self.partsCollectionView.register(SelectionCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
以编程方式注册单元格时,它会创建一个新的集合视图单元格对象。它没有从故事板中获取单元格。所以cellTitle
将为零
或强>
以编程方式初始化自定义集合视图单元格中的标签
class SelectionCollectionViewCell:UICollectionViewCell {
let cellTitle = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(cellTitle)
cellTitle.frame = CGRect(x: 10, y: 10, width: 100, height: 30)
}
}
答案 1 :(得分:2)