gpt4 book ai didi

ios - UITableViewCell 内的 UICollectionView 始终返回空,即使显示为选定状态

转载 作者:行者123 更新时间:2023-11-29 05:50:08 27 4
gpt4 key购买 nike

我在 UITableViewCell 中使用 UICollectionView。我可以选择 UICollectionView 内的单元格。但是当我尝试获取 UICollectionView 或选定的单元格时,结果始终为 null。我已经在这个问题上停留了很长时间。我在下面添加了我的代码供您引用。

class WeekDaysSelCell: UITableViewCell,UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

var weekdays = ["S", "M", "T", "W", "T", "F", "S"]

var weekdaysSelected = [String]()

@IBOutlet var weeklyDaysColView: UICollectionView!

override func awakeFromNib() {
super.awakeFromNib()
self.weeklyDaysColView.delegate = self
self.weeklyDaysColView.dataSource = self
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell : WeekDaysCollCell = weeklyDaysColView.dequeueReusableCell(withReuseIdentifier: "weekday", for: indexPath) as! WeekDaysCollCell

cell.weekDayLabel.text = weekdays[indexPath.row]
return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let cell : WeekDaysCollCell = self.weeklyDaysColView.cellForItem(at: indexPath) as! WeekDaysCollCell
if (cell.backgroundColor == UIColor.gray) {
cell.backgroundColor = UIColor.clear
weekdaysSelected.removeAll { $0 == String(indexPath.row)}
//print("Removed from weekdaysSelected:", indexPath.row)
} else {

cell.backgroundColor = UIColor.gray
cell.isSelected = true
//weeklyDaysColView.selectItem(at: indexPath, animated: true, scrollPosition: [])
weekdaysSelected.append(String(indexPath.row))
//print("Added to weekdaysSelected:", indexPath.row)
}
}
}

// Trying to get the collection view from inside a willMove(toParent parent: UIViewController?) method.

override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if parent == nil
{

if let delegate = self.delegate {
print("Inside If condition")

// Code that i use to get the cell
let cell3 = tableView.dequeueReusableCell(withIdentifier: "cell3") as! WeekDaysSelCell

print(cell3.weekdaysSelected)

print(cell3.weeklyDaysColView.indexPathsForSelectedItems)

// Trying to pass selected cells
//delegate.repeatCustomSelection(selectedIdx: String(lastSelection.row),repeatCustomSel: repeatCustomSelection)
}
}
}

最佳答案

您正在尝试在 willMove(toParent Parent: UIViewController?) 中获取可重用的单元格,这不会返回您预期的单元格。

您需要使用索引路径获取单元格。

func cellForRow(at indexPath: IndexPath) -> UITableViewCell?

关于ios - UITableViewCell 内的 UICollectionView 始终返回空,即使显示为选定状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com