Using a custom image for a UITableViewCell's accessoryView and having it respond to UITableViewDelegate

后端 未结 10 2067
独厮守ぢ
独厮守ぢ 2020-11-27 09:35

I\'m using a custom drawn UITableViewCell, including the same for the cell\'s accessoryView. My setup for the accessoryView happens by the way of something like

10条回答
  •  臣服心动
    2020-11-27 09:41

    Swift 5

    This approach uses the UIButton.tag to store the indexPath using basic bit-shifting. The approach will work on 32 & 64 bit systems as long as you don't have more than 65535 sections or rows.

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
        let accessoryButton = UIButton(type: .custom)
        accessoryButton.setImage(UIImage(named: "imageName"), for: .normal)
        accessoryButton.sizeToFit()
        accessoryButton.addTarget(self, action: #selector(handleAccessoryButton(sender:)), for: .touchUpInside)
    
        let tag = (indexPath.section << 16) | indexPath.row
        accessoryButton.tag = tag
        cell?.accessoryView = accessoryButton
    
    }
    
    @objc func handleAccessoryButton(sender: UIButton) {
        let section = sender.tag >> 16
        let row = sender.tag & 0xFFFF
        // Do Stuff
    }
    

提交回复
热议问题