UITableViewCell selector setSelected:animated: gets called many times?

前端 未结 4 640
野趣味
野趣味 2021-01-31 19:56

I\'ve discovered a strange behavior with setSelected:animated: in my custom UITableViewCell class. I discovered that this function gets called multiple times if

4条回答
  •  暖寄归人
    2021-01-31 20:27

    What's going on is simply that the UITableView keeps track of which cells are selected in the table.

    Since cells are reused when you scroll through a large table view, the table view has to keep the list of selected cells separate. Not only that, but whenever it reuses a cell it has to set its selected property, because it may be using an old, invalid selected state from a previous incarnation.

    When you tap a cell, several things happen: the previously selected cell is deselected (using setSelected:). The new cell is highlighted. It's de-highlighted (at least if you tap, instead of holding your finger down), and the setSelected: method is called because the new cell was selected. That's one.

    The second call is a delayed perform call, possibly from a point where the table view didn't yet know what the final state of the table would be. This call goes to _selectAllSelectedRows, which, as the name suggests, calls 'setSelected:animated:' on all selected rows. That's the second call. The reason for this is most likely to address potential issues due to the the table view being in a "transition", but who knows.

    Whether it's a bug or not is up for interpretation. A fix for the duplicate calls is to simply do:

    if (self.selected == selected) return;
    

    right before the call to super (you do not have to call super if self.selected == selected).

提交回复
热议问题