[英]ios pass data between custom view and view controller
I'm a beginner in iOS development. 我是iOS开发的初学者。 I have a custom view: 我有一个自定义视图:
@interface MyView : UIView {
In the ViewController, I add this view as a subview (would be better to do in another way, maybe in the Storyboard?): 在ViewController中,我将此视图添加为子视图(最好在故事板中用另一种方式来做?):
MyView *myView = [[MyView alloc]initWithFrame:myFrame];
[self.view addSubview:myView];
in it, I follow the touches on screen, and I have a touchesEnded method: 在其中,我遵循屏幕上的触摸,并且有一个touchesEnded方法:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// myValue is a class variable of MyView
myValue = doSomething();
}
Now, how can I get the value of myValue
in the ViewController? 现在,如何在ViewController中获取myValue
的值? Maybe a listener or a callback that can be invoked inside touchesEnded
in MyView? 也许可以在MyView中的touchesEnded
内部调用的侦听器或回调?
Well, a simple way is to keep a reference to the view controller in MyView
, eg, define a property like: 好吧,一种简单的方法是在MyView
保留对视图控制器的引用,例如,定义一个属性,例如:
@property (weak,nonatomic) MyViewController *viewController;
And then in the view controller assign myView.viewController = self
. 然后在视图控制器中分配myView.viewController = self
。 This way you can then call whatever methods on the view controller from MyView
, eg, [viewController myView:self changedValue:myValue]
or whatever. 这样,您就可以从MyView
调用视图控制器上的任何方法,例如[viewController myView:self changedValue:myValue]
或其他方法。
(And, yes, it's possible to add the custom view subclass directly in the storyboard. Just add a generic UIView
in the storyboard and change its class to MyView
.) (而且,是的,可以直接在情节UIView
中添加自定义视图子类。只需在情节UIView
中添加通用UIView
并将其类更改为MyView
。)
There are of course many alternative ways, eg, notifications, or simply polling a property of MyView
from the view controller if its only of interest at certain times, etc. 当然,有许多替代方法,例如,通知,或者仅在特定时间从视图控制器轮询MyView
的属性(如果仅在特定时间关注)等。
For instance, you can post a NSNotification in touchesEnded method of your view: 例如,您可以在视图的touchesEnded方法中发布NSNotification :
[[NSNotificationCenter defaultCenter] postNotificationName:@"ViewDidTouch" object:self];
Listen for this notification in your view controller. 在视图控制器中侦听此通知。 To achieve that add in the view controller's method viewDidLoad a line: 要实现这一点,请在视图控制器的方法viewDidLoad中添加一行:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onViewDidTouch:) name:@"ViewDidTouch" object:nil];
And then implement below method in your view controller: 然后在您的视图控制器中实现以下方法:
- (void) onViewDidTouch:(NSNotification*)notification
{
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.