问题描述
当plusBtnTapped 时,我需要从 TeamsVC 调用 TeamsCell 中的函数 deleteButtonShowHide。我试图用 protocol TeamsVCDelegate 来解决它,但它不起作用(它对我来说反之亦然。但我不知道如何实现像 cell.teamsCellDelegate = self 这样的东西
TeamsCell
trait Get<'a> {
fn get(slice: &'a [f32]) -> Self;
}
impl<'a> Get<'a> for () {
fn get(slice: &'a [f32]) -> Self {
()
}
}
impl<'a> Get<'a> for &'a [f32] {
fn get(slice: &'a [f32]) -> Self {
&slice[0..5]
}
}
TeamsVC
import UIKit
protocol TeamsCellDelegate {
func deleteCell()
}
class TeamsCell: UITableViewCell {
@IBOutlet weak var teamNameLbl: UILabel!
@IBOutlet weak var deleteButton: UIButton!
var teamsCellDelegate: TeamsCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func updateCell(team: team) {
teamNameLbl.text = team.name
}
@IBAction func deleteButtonTapped(_ sender: Any) {
debugPrint("delet tapped")
//deleteButtonShowHide()
findAndDeleteTeam()
teamsCellDelegate?.deleteCell()
}
func findAndDeleteTeam() {
for i in 0...teams.count - 1 {
if teams[i].name == teamNameLbl.text {
teams.remove(at: i)
break
}
}
}
func deleteButtonShowHide(){
if teams.count < 3 {deleteButton.isHidden = true}
if teams.count > 2 {deleteButton.isHidden = false}
}
}
extension TeamsCell: TeamsVCDelegate {
func deleteButtonSH() {
debugPrint("XXX")
deleteButtonShowHide()
}
}
解决方法
您可以在加载/设置单元格时调用 deleteButtonShowHide
函数:
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
cell.deleteButtonShowHide() // <-- HERE
cell.teamsCellDelegate = self
return cell
}
return UITableViewCell()
}
顺便说一下,您的单元格一开始就不应该包含这样的逻辑。它应该依赖于一些数据模型对象,然后应该使用它来正确设置您的单元格(显示/隐藏 UI 元素等)。
,您可以在计算行数时通过设置按钮显示/隐藏来简化。
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
if teams.count < 5 {plusBtn.isHidden = false}
if teams.count == 4 { plusBtn.isHidden = true}
return teams.count
}
并在创建单元格时设置删除按钮的可见性:
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
// cell.teamsCellDelegate = self
cell.deleteButton.isHidden = (teams.count < 3)
return cell
}
return UITableViewCell()
}
因此无需委托和单元不必了解模型(团队)