2014-06-16 59 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

相關問題