如何获取超视图的视图控制器的引用?

时间:2012-05-12 09:26:01

标签: objective-c controller superview

有没有办法获得我的superview的视图控制器的引用? 有几个例子我在过去几个月里需要这个,但不知道怎么做。我的意思是,如果我在自定义单元格上有自定义按钮,并且我希望得到控制我当前所在单元格的表视图控制器的引用,那么是否有一个代码片段?或者我应该通过使用更好的设计模式来解决它?

谢谢!

3 个答案:

答案 0 :(得分:3)

您的按钮最好不要知道其超级视图控制器。

但是,如果您的按钮确实需要发送不应该知道详细信息的对象,则可以使用委托将所需的消息发送给按钮委托。

创建一个MyButtonDelegate协议,并定义符合该协议的每个人需要实现的方法(回调)。您也可以使用可选方法。

然后在按钮@property (weak) id<MyButtonDelegate>上添加一个属性,以便任何类型的任何类都可以设置为委托,只要它符合您的协议即可。

现在视图控制器可以实现MyButtonDelegate协议并将其自身设置为委托。需要有关视图控制器知识的代码部分应该在委托方法(或方法)中实现。

视图现在可以将协议消息发送给其委托(不知道是谁或者是什么),并且委托可以为该按钮添加适当的内容。这样可以重复使用相同的按钮,因为它不依赖于它的使用位置。

答案 1 :(得分:0)

当我问这个问题时,我想到的是,在我有自定义单元格的情况下,TableViewController如何知道哪个单元格的按钮被点击了。 最近,在阅读“iOS食谱”一书时,我得到了解决方案:

-(IBAction)cellButtonTapped:(id)sender
{
NSLog(@"%s", __FUNCTION__);
UIButton *button = sender;

//Convert the tapped point to the tableView coordinate system
CGPoint correctedPoint = [button convertPoint:button.bounds.origin toView:self.tableView];

//Get the cell at that point
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:correctedPoint];

NSLog(@"Button tapped in row %d", indexPath.row);
}

另一个解决方案,更脆弱(虽然更简单)将是:

- (IBAction)cellButtonTapped:(id)sender 
{
    // Go get the enclosing cell manually
    UITableViewCell *parentCell = [[sender superview] superview];
    NSIndexPath *pathForButton = [self.tableView indexPathForCell:parentCell];
}

最可重用的方法是将此方法添加到UITableView

的类别中
- (NSIndexPath *)prp_indexPathForRowContainingView:(UIView *)view 
{
   CGPoint correctedPoint = [view convertPoint:view.bounds.origin toView:self]; 
   return [self indexPathForRowAtPoint:correctedPoint];
}

然后,在你的UITableViewController类上,只需使用:

- (IBAction)cellButtonTapped:(id)sender 
{
    NSIndexPath *pathForButton = [self.tableView indexPathForRowContainingView:sender];
}

答案 2 :(得分:-1)

如果您知道哪个类是视图控制器的超级视图,则可以遍历子视图数组和超类的类型检查。

例如

UIView *view; 

for(tempView in self.subviews) {

   if([tempView isKindOfClass:[SuperViewController class] ])

        {
           // you got the reference, do waht you want

         }


   }