【问题标题】:How to use touchesBegan from one UIView in another UIViewController如何从另一个 UIViewController 中的一个 UIView 使用 touchesBegan
【发布时间】:2014-06-16 19:34:04
【问题描述】:

我在名为 HeartrateGraph 的 UIView 中制作了一个包含数据的图表。在一个名为 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;
    }
}

这段代码在 touchesBegan 中,并在对象 graphInfoRF 中正确存储了数据值和数字(我只是没有显示 dataArray、kNumberOfPoints 等的声明)。

我可以使用以下方法访问 UIViewController 中的 graphInfoRF:

- (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 以便在我触摸图表上的数据点后,它会自动用数据填充标签,而无需再次单独触摸标签?

【问题讨论】:

    标签: objective-c xcode uiview uiviewcontroller touchesbegan


    【解决方案1】:

    所有 ViewController 都带有一个在初始化后管理的视图。你应该熟悉这个视图,每当你在 Interface Builder 中使用 ViewController 时都会看到它,如果你正在修改子类,你可以使用 self.view 访问它。

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

    所以发生的事情是,仅在触摸标签时才调用更改 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

    【讨论】:

    • 我最初设置项目的方式有点低效,因为图表是单独的UIView,但我太远了,无法更改格式。将我的事件传递给 superview 就可以了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多