How do I get the position of subview in my UITable

2019-05-03 03:18发布

问题:

I know convertRect:toRect is the key here, but I'm not sure how to call it. I have a subview of my cell, and I want its position in the app's entire window.

I need to know this when I tap on this button (the subview) in its target action method. I need to call the convertRect:toRect function on the cell, I figure, in order to get the right coordinates, but in this method I have no reference to the cell itself.

Do I climb the superview hierarchy? That seems gross, as I'm not totally sure what I would get, as it's embedded in the contentView of the cell, and Apple does wacky stuff with their private subviews and whatnot.

Code:

@IBAction buttonPressed(sender: UIButton) {
    // This button got the callback that it was pressed. It's in a cell. I need to convert its rect to that of the window here. I need the coordinate system it's calculated from (the cell) which I'm not sure of how to easily do in a target action callback.
}

回答1:

It's actually very simple:

CGRect windowRect = [someSubview convertRect:someSubview.bounds toView:nil];

Assuming you have a button handler:

- (void)someButtonHandler:(id)sender {
    UIButton *button = sender;

    // do your stuff

    CGRect windowRect = [button convertRect:button.bounds toView:nil];
}

Of course it's even easier if your method is setup as:

- (void)someButtonHandler:(UIButton *)button {
}