2014-06-16 24 views
0

我已经制作了一个名为HeartrateGraph的UIView中的数据图。在名为HRGraphInfo的UIViewController中,我有一个连接的标签,当图形被触摸时应该输出值。问题是,我不知道如何使用委托从UIView发送到UIViewController触摸的事件。如何使用touchesBegin从另一个UIViewController中的一个UIView

这里是UIView的我触摸分配代码:

UITouch *touch = [touches anyObject]; 
CGPoint point = [touch locationInView:self]; 

for (int i = 0; i < kNumberOfPoints; i++) 
{ 
    if (CGRectContainsPoint(touchAreas[i], point)) 
    { 
     graphInfoRF.heartRateGraphString = [NSString stringWithFormat:@"Heart Rate reading #%d at %@ bpm",i+1, dataArray[i]]; 
     graphInfoRF.touched = YES; 

     break; 
    } 
} 

这个代码段是一个的touchesBegan并妥善保存在对象graphInfoRF的数据值和号码(我只是没有显示的声明dataArray,kNumberOfPoints等)。

我能够访问graphInfoRF在UIViewController中使用:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 

if (graphInfoRF.touched == YES) { 
    self.heartRateLabel.text = graphInfoRF.heartRateGraphString; 

} 
else { 
    self.heartRateLabel.text = @"No data got over to this file";} 
} 

标签将显示正确的字符串,但图表中的数据点被触摸并且只有在标签后立即感动。如何更改touchesBegan,以便一旦我触摸图上的数据点,它就会自动填充标签,而不需要在标签上再次单独触摸?

回答

0

所有ViewController都带有一个初始化后管理的单个视图。您应该熟悉这个视图,无论何时在Interface Builder中使用ViewController都可以看到它,如果您要修改子类,则可以使用self.view来访问它。

由于ViewController带有一个视图,它也接收该视图的触摸事件。然后在ViewController中实现touchesBegan将接收该视图的事件,通常是该视图正在管理的任何子视图。由于您在HeartRateGraph中自己实现了'touchesBegan',并且由于HeartRateGraph是ViewControllers主视图的子视图,HeartRateGraph将在ViewController有机会接收和处理事件之前先接收并处理触摸事件它通常会(想起冒泡)。

所以发生了什么事时,改变的ViewController标签的代码只有当标签被触摸,因为标签是视图控制器的主视图的子视图...,也标签没有自己的touches实现调用,因此ViewController能够以您想要的方式检索和处理事件,只有当您单击图表外的某个位置时。如果你明白,那么有两种方法可以解决这个问题。

无论是传递事件到你上海华

[self.superview touchesBegan:touches withEvent:eventargs];

或做它的正确的推荐方式:

Protocols and Delegates where your View makes a delegate call to it ViewController letting it know the graph has been touched and the ViewController needs to update its contents

+0

我建立了我的项目最初的方式是因为有些低效该图是一个单独的'UIView',但我太过于改变格式。将我的活动传递给超级观点只是一招。非常感谢! – momodude22

相关问题