UITableViewCell Separator disappearing in iOS7

前端 未结 30 714
轮回少年
轮回少年 2020-12-07 08:31

I have some strange issue with UITableView only in iOS 7.

UITableViewCellSeparator disappears above the first row and below the last row. S

30条回答
  •  無奈伤痛
    2020-12-07 09:09

    A simple and clean solution that works on both iOS 8 and iOS 9 (beta 1)

    Here is a simple, clean and non-intrusive workaround. It involves calling a category method that will fix the separators.

    All you need to do is to walk down the hierarchy of the cell and un-hide the separator. Like this:

    for (UIView *subview in cell.contentView.superview.subviews) {
        if ([NSStringFromClass(subview.class) hasSuffix:@"SeparatorView"]) {
            subview.hidden = NO;
        }
    }
    

    What I recommend is to add this to a category on UITableViewCell, like this:

    @interface UITableViewCell (fixSeparator)
    - (void)fixSeparator;
    @end
    
    @implementation UITableViewCell (fixSeparator)
    
    - (void)fixSeparator {
        for (UIView *subview in self.contentView.superview.subviews) {
            if ([NSStringFromClass(subview.class) hasSuffix:@"SeparatorView"]) {
                subview.hidden = NO;
            }
        }
    }
    
    @end
    

    Because the separator can disappear in different cell than the one currently selected, it's probably a good idea to call this fix on all cells in the table view. For that, you can add a category to UITableView that goes like this:

    @implementation UITableView (fixSeparators)
    
    - (void)fixSeparators {
        for (UITableViewCell *cell in self.visibleCells) {
            [cell fixSeparator];
        }
    }
    
    @end
    

    With this in place, you can call -fixSeparatos on your tableView right after the action that causes them to disappear. In my case, it was after calling [tableView beginUpdates] and [tableView endUpdates].

    As I stated at the beginning, I've tested this on both iOS 8 and iOS 9. I presume it will work even on iOS 7 but I don't have a way to try it there. As you are probably aware, this does fiddle with internals of the cell so it could stop working in some future release. And Apple could theoretically (0.001% chance) reject your app because of this, but I can't see how they could even find out what you are doing there (checking the suffix of a class can't be detected by static analyzers as something bad, IMO).

提交回复
热议问题