Reference from UITableViewCell to parent UITableView?

前端 未结 7 1736
有刺的猬
有刺的猬 2020-11-29 04:02

Is there any way to access the owning UITableView from within a UITableViewCell?

7条回答
  •  猫巷女王i
    2020-11-29 04:42

    The two methods in other answers are: (A) store a reference to the table, or (B) walk up the superviews.

    I'd always use something like (A) for model objects and (B) for table cells.

    Cells

    If you are dealing with a UITableViewCell, then AFAIK you must either have the UITableView at hand (say you are in a table delegate method), or are dealing with a visible cell that is in the view hierarchy. Otherwise, you may well be doing something wrong (please note the "may well").

    Cells are liberally reused and if you happen to have one that is not visible then the only real reason that cell exists is because of iOS UITableView performance optimization (a slower iOS version would have released and hopefully dealloc'd the cell when it moved off screen) or because you have a specific reference to it. I guess this is probably the reason that table cells are not endowed with a tableView instance method.

    So (B) gives the right result for all iOS's so far, and all future ones until they radically change how views work.

    Though in order to avoid writing generalizable code over and over, I'd use this:

    + (id)enclosingViewOfView:(UIView *)view withClass:(Class)returnKindOfClass {
      while (view&&![view isKindOfClass:returnKindOfClass]) view=view.superview;
      return(view);
    }
    

    and a convenience method:

    + (UITableView *)tableForCell:(UITableViewCell *)cell {
      return([self enclosingViewOfView:cell.superview withClass:UITableView.class]);
    }
    

    (or categories if you like)

    BTW, if you are concerned about the effect of a loop with 20 or so iterations of that size on your app performance,.. don't.

    Models

    If you are talking about the model object that is displayed in the cell, then definitely that model could/should know about its parent model, which may be used to find, or trigger changes in, the table(s) that the cell's model might be displayed in. This is like (A), but less brittle with future iOS updates (eg one day they might make the UITableViewCell reuse cache exist per reuseidentifier, rather than per reuseidentifier per tableview, on that day all the implementations that use the weak reference method will break).

    Th model method would be used for changes to the data displayed in the cell (i.e. model changes) since changes will propagate wherever the model is displayed (eg. some other UIViewController somewhere else in the app, logging, ...)

    The cell method would be used for tableview actions, which would likely always be a bad idea if the cell isn't even a subview of a table (though it's your code, go nuts).

    Either way, use a unit test rather than assuming that seemingly cleaner code just works when they update iOS.

提交回复
热议问题