Objective c 如何使用触摸从另一个UIViewController中的一个UIView开始

Objective c 如何使用触摸从另一个UIViewController中的一个UIView开始,objective-c,xcode,uiview,uiviewcontroller,touchesbegan,Objective C,Xcode,Uiview,Uiviewcontroller,Touchesbegan,我用UIView中的数据制作了一个名为HeartrateGraph的图形。在名为HRGraphInfo的UIViewController中,我有一个连接的标签,当触摸图形时,该标签应输出值。问题是,我不知道如何使用UIView中的代理将触摸事件发送到UIViewController 以下是UIView中的我的触摸分配代码: UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; for

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

以下是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;
    }
}

标签将显示正确的字符串,但仅在触摸图形上的数据点以及触摸标签之后。如何更改触摸开始,以便在触摸图形上的数据点后,它将自动用数据填充标签,而无需再次单独触摸标签?

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

由于ViewController附带一个视图,因此它还接收该视图的触摸事件。然后,在ViewController中开始实现TouchesStart将接收该视图的事件,通常包括该视图正在管理的任何子视图。由于您已经在HeartRateGraph中完成了自己的“touchesStart”实现,并且HeartRateGraph是ViewControllers主视图的子视图,因此HeartRateGraph将在ViewControllers有机会接收和处理事件之前首先接收和处理触摸事件,就像它通常认为的冒泡一样

所以现在发生的是,更改ViewController中标签的代码仅在触摸标签时调用,因为标签是ViewController主视图的子视图。。。此外,label没有自己的Touchs实现,因此ViewController和VisualController只能在单击图形之外的某个位置时以您想要的方式检索和处理事件。如果你明白了,那么有两种方法可以解决这个问题

或者将事件传递给superview

[self.superview touchsbegind:touchswithevent:eventargs]

或正确的推荐方法:


协议和委托,其中您的视图对其进行委托调用ViewController,让其知道图形已被触摸,并且ViewController需要更新其内容

我最初设置项目的方式有点效率低下,因为图形是一个单独的UIView,但我太投入了,无法更改格式。将我的活动传递给superview正好起到了作用。非常感谢你!
- (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";}
}