ios,从视图中获取指向控制器的指针 [英] ios, getting a pointer to a controller from a view

查看:158
本文介绍了ios,从视图中获取指向控制器的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个ios UI元素,我可以将屏幕上的项目拖到tableView上,tableView将添加相应的元素。我正在使用hitTest函数来识别我正在拖动元素的视图,并且工作正常。我的问题是,当我需要指向tableView的控制器的指针时,hitTest会给我一个指向tableView的指针,以便我可以调用添加新项功能。如何从指向视图的指针转到指向该视图控制器的指针?

I'm trying to make an ios UI element where I can drag items on the screen onto a tableView and the tableView will add corresponding elements. I'm using the hitTest function to identify which view I'm dragging elements onto, and that's working fine. My problem is that hitTest gets me a pointer to a tableView, when I need the pointer to the tableView's controller so that I can call an "add new item" function. How do I go from a pointer to a view to a pointer to that view's controller?

推荐答案

视图控制器是响应链。因此,从任何视图,只需继续调用 nextResponder ,直到您到达一个视图控制器的对象。

The view controller is part of the responder chain. So from any view, just keep calling nextResponder until you reach an object that is a view controller.

UIResponder* r = someView;
while (![r isKindOfClass: [UIViewController class]])
    r = [r nextResponder];
UIViewController* vc = (UIViewController*)r;

当您需要从视图中调用视图控制器中的方法时,另一个非常酷的技巧是使用无目标行动。这是因为没有针对性的行动走在响应者链上寻找处理行动的人。例如,这里的代码将按钮的动作设置为nil-targeted:

Another very cool trick when you need to call a method in your view controller from a view is to use a nil-targeted action. That's because a nil-targeted action walks up the responder chain looking for someone who handles the action. For example, here's code that sets a button's action to be nil-targeted:

[b addTarget:nil action:@selector(doButton:)
   forControlEvents:UIControlEventTouchUpInside];

如果视图控制器实现 doButton:,点击此按钮时将调用它。

If the view controller implements doButton:, it will be called when this button is tapped.

这篇关于ios,从视图中获取指向控制器的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆