2015-07-13 21 views
-1

斯威夫特相當於該目標C爲我工作,但我不能爲我的生命得到它在斯威夫特工作:的訪問的UILabel

- (IBAction)acceptWeight:(UIButton *)sender { 
    int tempValue = (int) currentWeight; 
    // current weight comes from a UISegementedController 

    for (UILabel *labels in self.view.subviews) 
    { 
     if (labels.tag == currentWeight) 
     { 
     bags[tempValue]++; 
     labels.text = [NSString stringWithFormat:@"%i",bags[tempValue]]; 
     } 
    } 
    totalKilo = totalKilo + (int)currentWeight; 
    self.totalKilo.text = [NSString stringWithFormat:@"%d",totalKilo]; 
} 

我想一般訪問的一個動態調整UILabels的數量,並更新其內容。

有一個工具,我在這裏ojectivec2swift.net試過,但同時t'was在轉換了大膽的嘗試,它並沒有削減芥末

它給

labels.text = [NSString stringWithFormat:@"%i",bags[tempValue]]; 

,因爲這相當於:

labels.text = "\(bags[tempValue])" 
// compiler warns.. Cannot assign to 'text' in 'labels' 

披露:這是基於我在這裏問的一個問題: iPhone - how to select from a collection of UILabels? (並在最後沒有o如果答案對我來說確實如此,那麼我最終會試驗我的方式。爲了完整起見 [按要求]這是在上下文中

@IBAction func acceptWeight(sender: UIButton) { 
    var tempValue: Int = currentWeight 

    for labels: UILabel in self.view.subviews { 
     if labels.tag == currentWeight { 
      bags[tempValue]++ 
      labels.text = "\(bags[tempValue])" 
     } 
    } 
    totalKilo = totalKilo + currentWeight 
    self.totalKilo.text = "\(totalKilo)" 
} 
+1

您發佈的Objective-C代碼沒有幫助,也沒有添加到討論中。如果您想要解決此問題的任何幫助,請嘗試用實際完整的Swift實現替換該代碼。你已經發布了一行Swift和一條錯誤消息。您沒有向我們展示出現錯誤的上下文。你要求我們猜測上下文。 – nhgrif

回答

1

整個SWIFT代碼功能:)所有我最近SWIFT相關搜索商量不,很合身接近


編輯您正在假設所有子視圖都是UILabel。只要你添加一個按鈕,它就會中斷。試試這個:

@IBAction func acceptWeight(sender: UIButton) { 
    var tempValue = currentWeight 

    for subview in self.view.subviews { 
     if let label = subview as UILabel where label.tag == currentWeight { 
      bags[tempValue] += 1 
      label.text = "\(bags[tempValue])" 
     } 
    } 
    totalKilo = totalKilo + currentWeight 
    self.totalKilo.text = "\(totalKilo)" 
} 
+0

是的!有效!!但您正確瞭解視圖中其他UI元素的標記值。奇怪的是,我現在單挑出的作品之前沒有。當我們不適用於If(...)條件時,我只能困惑於如何優雅地清除文本。謝謝。 – aremvee