如何在给定 UITextView 的情况下获取 UIViewController?
我正在 UITextViewDelegate 中处理代码。那里的每个函数都会接收接收事件的 UITextView 实例,例如:
- (void)textViewDidBeginEditing:(UITextView*)textView { }
但是,在该方法内,仅给定 textView,我需要访问包含 textView 的 UIViewController。
使用 textView.superview
(甚至它的多个阶段)似乎不起作用 - 我只得到:
- textView.superview.superview的实例
- textView.superview = UIView textView.superview.superview = UIViewControllerWrapperView
- 。 superview = UINavigationTransitionView
- textView.superview.superview.superview.superview = UILayoutContainerView
- textView.superview.superview.superview.superview.superview = UIWindow
- textView.superview.superview.superview.superview.superview.superview = nil
我通过打印找到了类名类似的东西
printf( "class: %s\n", [[[uiv class] description] UTF8String] ) ;
I'm handling code in a UITextViewDelegate. Each function there receives the UITextView instance that received the event, for example:
- (void)textViewDidBeginEditing:(UITextView*)textView { }
Inside that method however, only given the textView, I need to access the UIViewController that contains the textView.
Using textView.superview
(even multiple stages of it) doesn't seem to work - I only get:
- textView.superview = an instance of UIView
- textView.superview.superview = UIViewControllerWrapperView
- textView.superview.superview.superview = UINavigationTransitionView
- textView.superview.superview.superview.superview = UILayoutContainerView
- textView.superview.superview.superview.superview.superview = UIWindow
- textView.superview.superview.superview.superview.superview.superview = nil
I found the class names by printing out something like
printf( "class: %s\n", [[[uiv class] description] UTF8String] ) ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有办法做到这一点。 UIViewController 知道它管理什么 UIView,但视图没有对其视图控制器的引用(甚至可能没有视图控制器)。
-superview 方法返回另一个 UIView,它与 UIViewController 不同。
为什么需要视图控制器?你想实现什么目标?
顺便说一句,您可以使用 NSLog 而不是 printf 来节省一些击键次数:
There is no way to do this. A UIViewController knows what UIView it manages, but a view does not have a reference back to its view controller (and might not even have a view controller).
The -superview method returns another UIView, which is not the same thing as a UIViewController.
Why do you need the view controller? What are you trying to accomplish?
As an aside, you could save yourself a few keystrokes by using NSLog instead of printf:
出于好奇,为什么你的视图控制器不充当 UITextViewDelegate ?在我见过的大多数代码(包括我自己的代码)中,视图控制器本身往往充当委托。
如果您需要将此功能提取到一个单独的类中,也许视图控制器可以将对自身的引用传递给 UITextViewDelegate。
Out of curiosity, why isn't your view controller acting as the UITextViewDelegate? In most of the code I've seen (including my own), the view controllers themselves tend to act as delegates.
If you need to extract this functionality into a separate class, perhaps the view controller could pass a reference to itself to the UITextViewDelegate.