How to get the indexpath.row when an element is activated?

前端 未结 19 2254
梦如初夏
梦如初夏 2020-11-21 23:30

I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped. This is what I currently have, but it always is 0

var point =         


        
19条回答
  •  伪装坚强ぢ
    2020-11-22 00:05

    USING A SINGLE TAG FOR ROWS AND SECTIONS

    There is a simple way to use tags for transmitting the row/item AND the section of a TableView/CollectionView at the same time.

    Encode the IndexPath for your UIView.tag in cellForRowAtIndexPath :

    buttonForCell.tag = convertIndexPathToTag(with: indexPath)
    

    Decode the IndexPath from your sender in your target selector:

        @IBAction func touchUpInsideButton(sender: UIButton, forEvent event: UIEvent) {
    
            var indexPathForButton = convertTagToIndexPath(from: sender)
    
        }
    

    Encoder and Decoder:

    func convertIndexPathToTag(indexPath: IndexPath) -> Int {
        var tag: Int = indexPath.row + (1_000_000 * indexPath.section)
        
        return tag
    }
    
    func convertTagToIndexPath(from sender: UIButton) -> IndexPath {
        var section: Int = Int((Float(sender.tag) / 1_000_000).rounded(.down))
        var row: Int = sender.tag - (1_000_000 * section)
    
        return IndexPath(row: row, section: section)
    }
    

    Provided that you don’t need more than 4294967296 rows/items on a 32bit device ;-) e.g.

    • 42949 sections with 100_000 items/rows
    • 4294 sections with 1_000_000 items/rows - (like in the example above)
    • 429 sections with 10_000_000 items/rows

    —-

    WARNING: Keep in mind that when deleting or inserting rows/items in your TableView/CollectionView you have to reload all rows/items after your insertion/deletion point in order to keep the tag numbers of your buttons in sync with your model.

    —-

提交回复
热议问题