2014-05-08 69 views
-1

我在每個單元格中有一個帶有3個標籤的UITableView;活動名稱,持續時間和會見。值來自用戶輸入,存儲在活動數組中,然後顯示在表中。我不知道該怎麼做,就是將每個單元格中'met'值的值相加,並在tableView之外的另一個標籤中顯示該總和。找到每個單元格中每個標籤的總和

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *cellReuseIdentifier = @"CellReuseIdentifier"; 
    TestCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier]; 
    if (cell == nil) { 
     cell = [[TestCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseIdentifier]; 
    } 

    MyActivity *activity=(MyActivity *)[self.activities objectAtIndex:indexPath.row]; 

    NSString *name = [NSString stringWithFormat:@"Activity Name: %@",activity.description]; 

    NSString *value = [NSString stringWithFormat:@"Activity Duration: %d minutes",activity.duration]; 

    NSString *met = [NSString stringWithFormat:@"Your MET: %d minutes",activity.duration* activity.intensity]; 

    cell.activityLabel.text = name; 
    cell.durationLabel.text = value; 
    cell.metLabel.text = met; 
    return cell; 
} 
+0

只是循環你的活動數組? –

回答

1

單元格僅用於演示文稿,不能從單元格獲取數據。我建議你編寫一個函數來遍歷數組,以總結所有內容並更新表視圖之外的標籤。

你可以寫一個自定義的重載方法類似:

-(void)computeAndReloadData 
{ 
    [self computeSum]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 

     [tableView reloadData]; 
    }); 
} 
-1

試試這個

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section   
{ 

     double totalMet = 0.0f; 

     for (MyActivity* aActitivity in activities) { 

      totalMet = totalMet + (activity.duration* activity.intensity); 

     } 
     outsideLabel.text = [NSString stringWithFormat:@"%f",totalMet]; 

    return [activities count]; 
    } 
+1

將和邏輯包含在'numberOfRows'中的具體原因是什麼? – GoodSp33d

+0

每當您重新加載數據時,它也會更新外部標籤。沒有必要有獨立的功能,並呼籲每個重新加載數據。:) –

+0

那很好。不知道爲什麼倒票有:| – GoodSp33d

0

您可以快速枚舉數組與陣列狀

CGFloat metTotal; 
for (MyActivity *eachAct in self.activities) { 
    CGFloat met = eachAct.duration * eachAct.intensity; 
    metTotal = metTotal + met; 
} 

label.text = [NSString stringWithFormat:@"%f",metTotal]; 
+0

謝謝!我已經在我的UITableView代碼中添加了它,這是正確的嗎?它不會在我的標籤 – user3594689

+0

沒有返回任何東西。您可以在檢索數據後將其添加到viewDidLoad中 – manujmv

0

計算總和:

-(int)sum 
{ 
    int sum = 0; 
    for(int i = 0; i < self.activities.count; i++) 
    { 
     MyActivity *activity=(MyActivity *)[self.activities objectAtIndex:i]; 
    sum += [activity.duration intValue]; 
    } 
    return sum; 
} 
相關問題