Getting UITableViewCell with superview in iOS 7

前端 未结 5 1987
栀梦
栀梦 2021-01-04 20:18

I\'m getting the UITableViewCell a UIButton belongs to like this:

-(void)buttonHandler:(UIButton *)button {

    OrderCell *cell = [[button superview] superv         


        
相关标签:
5条回答
  • 2021-01-04 20:57

    To complete the answer of @thomas-keuleers this is the swift method:

    extension UIView {
    
        func findSuperViewWithClass<T>(superViewClass : T.Type) -> UIView? {
    
            var xsuperView : UIView!  = self.superview!
            var foundSuperView : UIView!
    
            while (xsuperView != nil && foundSuperView == nil) {
    
                if xsuperView.self is T {
                    foundSuperView = xsuperView
                } else {
                    xsuperView = xsuperView.superview
                }
            }
            return foundSuperView
        }
    
    }
    

    and you simply call like that:

    child.findSuperViewWithClass(TableViewCell)
    
    0 讨论(0)
  • 2021-01-04 20:57

    A shorter Version in swift 5

    extension UIView {
       var xsuperView = self.superview
    
       while xsuperView != nil {
            if let superView = xsuperView.self as? T {
                return superView
            } else {
                xsuperView = xsuperView?.superview
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-04 21:00

    The best way to do this is:

    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    UITableViewCell *cell = (UITableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
    
    0 讨论(0)
  • 2021-01-04 21:09
    if ([[button superView] isKindOfClass:[UITableViewCell class]]) {
    
    }
    
    else //check next :
    
    0 讨论(0)
  • 2021-01-04 21:10

    A better solution is to add a category for UIView(SuperView), and calling it by:

    UITableViewCell *cell = [button findSuperViewWithClass:[UITableViewCell class]]
    

    This way, your code works for all future and past iOS versions

    @interface UIView (SuperView)
    
    - (UIView *)findSuperViewWithClass:(Class)superViewClass;
    
    @end
    
    
    @implementation UIView (SuperView)
    
    - (UIView *)findSuperViewWithClass:(Class)superViewClass {
    
        UIView *superView = self.superview;
        UIView *foundSuperView = nil;
    
        while (nil != superView && nil == foundSuperView) {
            if ([superView isKindOfClass:superViewClass]) {
                foundSuperView = superView;
            } else {
                superView = superView.superview;
            }
        }
        return foundSuperView;
    }
    @end
    
    0 讨论(0)
提交回复
热议问题