2015-07-13 50 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