ios - 表格 View 中每个部分的 UiTableViewCell 单选复选标记
<p><p>如何使用自定义单元格对每个部分进行复选标记单选,当我意识到此代码时,单元格没有标记</p>
<pre><code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let it = PayMentSection(rawValue: indexPath.section) else {return}
switch it {
case .delivering:
let cell = tableView.dequeueReusableCell(withIdentifier: cellid) as! MakePaymentTableViewCell
cell.checkBox.isChecked = true
cell.accessoryType = .checkmark
case .ordering:
let cell2 = tableView.dequeueReusableCell(withIdentifier: cellid2) as! MakePaymentTableViewCell2
cell2.checkBox.isChecked = true
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
guard let it = PayMentSection(rawValue: indexPath.section) else {return}
switch it {
case .delivering:
let cell = tableView.dequeueReusableCell(withIdentifier: cellid) as! MakePaymentTableViewCell
cell.checkBox.isChecked = false
cell.accessoryType = .none
case .ordering:
let cell2 = tableView.dequeueReusableCell(withIdentifier: cellid2) as! MakePaymentTableViewCell2
cell2.checkBox.isChecked = false
cell2.accessoryType = .none
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>首先,像这样实现<code>UITableViewDelegate的</code> <strong><code>tableView(_:willSelectRowAt:)</code></strong>方法,</p>
<pre><code>func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let selectedIndexPathsInSection = tableView.indexPathsForSelectedRows?.filter({ $0.section == indexPath.section }), !selectedIndexPathsInSection.isEmpty {
selectedIndexPathsInSection.forEach({ tableView.deselectRow(at: $0, animated: false) })
}
return indexPath
}
</code></pre>
<p>接下来,在 <code>MakePaymentTableViewCell</code> 和 <code>MakePaymentTableViewCell2</code> 单元格中,覆盖 <strong><code>setSelected(_:animated:)</code></strong> 方法,即</p>
<pre><code>class MakePaymentTableViewCell: UITableViewCell {
//rest of the code...
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
self.checkBox.isChecked = selected
}
}
</code></pre>
<p>不需要实现 <code>didSelectRowAt</code> 和 <code>didDeselectRowAt</code> 方法。</p>
<p> <a href="/image/nzj61.gif" rel="noreferrer noopener nofollow"><img src="/image/nzj61.gif" alt="enter image description here"/></a> </p></p>
<p style="font-size: 20px;">关于ios - 表格 View 中每个部分的 UiTableViewCell 单选复选标记,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/57781891/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/57781891/
</a>
</p>
页:
[1]