iOS UIView中的坐标转换convertPoint --- iOS开发系列 ---项目中成长的知识六

如果你的UITableViewCell里面有一个Button需要响应事件,你会怎么做?

在Controller中使用 button父类的父类?   例如:UITableViewCell *parentCell = [[button superview]superview];

 这种方式可能是最快的,但是这样的问题是,它很脆弱,如果我们一旦把按钮向上或者向下移动一个层次,那么代码立刻就会出错,而且此时我们却很难发现出错的原因

所以,幸好UIView为我们提供了查找视图所在行的简洁方法,实现视图坐标系间的坐标转换

-convertPoint:toView: 方法

//转化为正确的坐标
- (IBAction)detailBtnCliched:(id)sender {
    UIButton *button = sender;

  CGPoint correctedPoint = [button convertPoint: button.bounds.origin
                                         toView:self.mytableview];
   NSIndexPath *indexPath =  [self.mytableview  indexPathForRowAtPoint:correctedPoint];
  NSLog(@"indexpath == %d", indexPath.row);

  //实现Button点击的方法
   //  [self jumpToDetailVC:indexPath.section];
}

本方法针对查找嵌入表哥单元格的控件源于何处的问题,提供了一个简洁的解决方法,适用于表哥或者单元格的各种布局

UIView 还提供了其他的转换坐标的方法

// 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;

 
// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
// 将rect从view中转换到当前视图中,返回在当前视图中的rect - (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;

注:在我们的项目中我是为这个方法建立了一个属于UITableview的Category方法,这样可以移植到其他项目中进行使用!

原文地址:https://www.cnblogs.com/WayneLiu/p/4925277.html