Search code examples
iosobjective-cuitableviewcgrect

Get position of UIButton in UITableViewCell


I have a button in a static UITableViewCell. What I want to do is place a UIView at the buttons location.

If I just get the buttons position, it will give me a position relative to the tableviews cell, not from the top of the tableViewController. What I want is get the buttons position from the top of the tableViewController.

For example: If the button is 8px away from the top of the current cell, but 57px away from the top of the viewController, I want to place the UIView at 57px.

Here's my code:

- (void)viewDidLoad {
    CGPoint buttonPosition = [button convertPoint:CGPointZero fromView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];

    CGRect rect = [myTableView rectForRowAtIndexPath:indexPath];

    NSLog(@"%f, %f", rect.origin.y, rect.origin.x);

    self.infoView = [[UIView alloc] initWithFrame:CGRectMake(button.frame.origin.x, button.frame.origin.y, 220, 110)];
}

The output of the nslog is 0.

I would also like to update the UIView's position whenever the iphone goes to landscape mode.


Solution

  • CGPoint originalPoint = button.frame.origin;
    CALayer *layer = self;
    CGPoint point = originalPoint;
    while (layer.superlayer)
    {
        point = [layer convertPoint:point toLayer:layer.superlayer];
        layer = layer.superlayer;
    }
    
    //When you reach this code, you should have the position in the rootView