得到一个UITableView实例:@IBOutlet var showHomeTBView: UITableView?
// MARK: - UITableViewDataSource UITableViewDelegate func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return self.itemsArray!.count } func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell { var showHoMetableViewCell: ShowHoMetableViewCell! showHoMetableViewCell = self.showHomeTBView!.dequeueReusableCell(withIdentifier: "ShowHoMetableViewCellIdentifier",for: indexPath) as? ShowHoMetableViewCell showHoMetableViewCell!.showImageView!.image = UIImage(named: "ball-Image") showHoMetableViewCell?.showNameLabel?.text = self.itemsArray![indexPath.row] as? String showHoMetableViewCell.delegate = self return showHoMetableViewCell } func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat { return 160 } func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) { self.selectedIndexPath = indexPath //self.performSegue(withIdentifier: "gotoDetailViewController",sender: self) self.showHomeTBView?.deselectRow(at: indexPath,animated: true) } // MARK: - TableViewCell delegate func doSelect(_ sender: Any) { /* UIView *view = [button superview]; GameForPlaceTableViewCell *gameForPlaceTableViewCell = (GameForPlaceTableViewCell *)[view superview]; NSIndexPath *indexPath = [self.gameForPlaceTBView indexPathForCell:gameForPlaceTableViewCell]; self.selectedIndexPath = indexPath; */ let view = (sender as! UIButton).superview let showHoMetableViewCell = view!.superview as! ShowHoMetableViewCell let indexPath = self.showHomeTBView!.indexPath(for: showHoMetableViewCell) self.selectedIndexPath = indexPath self.performSegue(withIdentifier: "gotoDetailViewController",sender: self) }
自定义UITableViewCell:
class ShowHoMetableViewCell: UITableViewCell { @IBOutlet var showImageView: UIImageView? @IBOutlet var showNameLabel: UILabel? @IBOutlet var selectButton: UIButton? var delegate: ShowHoMetableViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.selectButton!.layer.cornerRadius = 15 self.selectButton!.layer.masksToBounds = true self.selectButton!.backgroundColor = UIColor.blue } override func setSelected(_ selected: Bool,animated: Bool) { super.setSelected(selected,animated: animated) // Configure the view for the selected state } @IBAction func doSelect(_ sender: Any) { if delegate != nil { delegate!.doSelect(sender) } } }
点击自定义的UITableViewCell上得button时用代理传递:
protocol ShowHoMetableViewCellDelegate { func doSelect(_ sender: Any) }
实现vc的跳转:
// MARK: - Transmit data override func prepare(for segue: UIStoryboardSegue,sender: Any?) { let detailVC = segue.destination as! DetailViewController if segue.identifier == "gotoDetailViewController" { detailVC.nameStr = self.itemsArray![self.selectedIndexPath!.row] as? String } }