我从故事板创建了UItableView,这是我如何使用cellForRowAt indexPath func
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let titleCell = tableView.dequeueReusableCell(withIdentifier: "titleCell", for: indexPath) as! MenuTableViewCell
titleCell.label.text = newsTitle
return titleCell
}else if indexPath.row == 1 {
let collectionViewCell = tableView.dequeueReusableCell(withIdentifier: "collectionViewCell", for: indexPath) as! collectionViewCell
return collectionViewCell
}
let cell = UITableViewCell()
return cell
}
我已经以编程方式为UICollectionView创建了这个类:
private class collectionViewCell : UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
private let reuseableCell = "CellId"
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseableCell)
}
override func layoutSubviews() {
super.layoutSubviews()
}
let imagesCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionViewScrollDirection.horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
return collectionView
}()
func setupViews() {
backgroundColor = UIColor.black
addSubview(imagesCollectionView)
imagesCollectionView.dataSource = self
imagesCollectionView.delegate = self
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": imagesCollectionView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": imagesCollectionView]))
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = UICollectionViewCell()
cell.backgroundColor = .green
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: frame.height - 68)
}
}
如您所见,我已经更改了UICollectionView及其单元格的颜色,但在UITableView中没有任何颜色。
在我运行应用程序后没有任何事情发生,所以我在这里犯了什么错误?
答案 0 :(得分:1)
似乎没有调用您的setupViews()
方法。请考虑在初始化程序中调用它。
答案 1 :(得分:-1)
您尝试在UITableViewCell
中继承UICollectionViewCell
。
此:
private class collectionViewCell : UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate
应该是:
private class collectionViewCell : UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate