【发布时间】:2019-10-24 12:30:18
【问题描述】:
我有一个 UICollectionView,里面有 4 个视图。这些视图中的每一个都有一个带有自定义单元格的 UITableView。 UITableView 的每个单元格内部都有一个 UIButton,每个 UITableView 有 2 个单元格。
发生了一些奇怪的事情。我对每个按钮都有一个动作功能,这样当一个按钮被点击时,它就会变成紫色。奇怪的是:如果我滚动到收藏视图的第 4 个视图并单击一个按钮,它会按预期变为紫色,但是当我滚动到收藏视图的第一个视图时,与我在第四个视图(第一个或第二个)也是紫色的,好像我的集合视图的第四个视图引用了我的集合视图的第一个视图的项目。
我不知道第一个视图在什么时候与第四个视图相同,但这里是代码示例:
// this is the cellForItemAt of my UICollectionView, very basic
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellView = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PollCellView
return cellView
}
// THIS IS ANOTHER FILE HERE
// this is part of my view that populate the UICollectionViews
class PollCellView: UICollectionViewCell {
// the table view
let questAndAnswersTableView : UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.separatorStyle = .none
tableView.allowsSelection = false
return tableView
}()
// I add the tableview in the view here
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(questAndAnswersTableView)
// a classic cellForRowAt of my UITableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AnswerCell2", for: indexPath) as! AnswerCell2
return cell
}
// THIS IS ANOTHER FILE HERE
// this part is my custom cell of the UITableView
class AnswerCell2: UITableViewCell {
let answerTextButton: UIButton = {
let answerButton = UIButton()
answerButton.setTitle("initial text", for: .normal)
return answerButton
}()
// I add the button to the cell here
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(answerTextButton)
// I define the action function
answerTextButton.addTarget(self, action: #selector(answerClicked), for: .touchUpInside)
}
// the action to make the button purple
@objc func answerClicked(sender: UIButton) {
sender.backgroundColor = UIColor(displayP3Red: 0.6902, green: 0.7176, blue: 0.9922, alpha: 1.0)
}
[根据收到的答案进行编辑]
出队绝对不像最初看起来那么简单...您不能相信在给定集合视图中出队的表格视图确实是您所期望的...您需要跟踪内容(模型)你自己。更容易修复的一件事是在 TableView 的单元格和 UICollectionViewCell 的单元格之间使用闭包......您可以非常轻松地将数据从一个传递到另一个(例如单击了什么 indexPath 等)。
【问题讨论】:
标签: ios swift uitableview uicollectionview