问题描述
我在一个视图控制器中创建了两个集合视图。出于未知原因,我无法从UILabel获取文本以进行第二个集合视图。
我的代码:
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
@IBOutlet weak var mainNumbers: UICollectionView!
@IBOutlet weak var horizontalNumbers: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
mainNumbers.delegate = self
mainNumbers.dataSource = self
horizontalNumbers.delegate = self
horizontalNumbers.dataSource = self
}
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
if collectionView == mainNumbers {
return 81
} else {
return 5
}
}
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == mainNumbers {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath) as! MainCell
cell.label.text = "f"
cell.backgroundColor = .systemGreen
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell2",for: indexPath) as! CellSecond
cell.cellSecond.text = "fds"
cell.backgroundColor = .systemGreen
return cell
}
}
}
class MainCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
class CellSecond: UICollectionViewCell {
@IBOutlet weak var cellSecond: UILabel!
}
解决方法
第一件事:无需创建两个不同的类。像这样创建一个:
class MyCollectionViewCell: UICollectionViewCell {
let label: UILabel = {
let lab = UILabel()
lab.translatesAutoresizingMaskIntoConstraints = false
lab.contentMode = .scaleAspectFit
lab.font = UIFont.systemFont(ofSize: 15)
lab.clipsToBounds = true
lab.numberOfLines = 3
return lab
}()
override init(frame: CGRect) {
super.init(frame: .zero)
contentView.addSubview(label)
label.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
label.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
label.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
现在像您一样注册两个单元格,但是将它们分别分配给MyCollectionViewCell
并调用cell.label.text = "whateverYouWant"
。