ios - Swift equivalent of UILabel access -


this worked me in objective c, can't life of me work in swift:

- (ibaction)acceptweight:(uibutton *)sender {    int tempvalue = (int) currentweight;   // current weight comes uisegementedcontroller     (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]; } 

i'm trying generically access 1 of number of uilabels dynamically, , update contents.

there tool tried here ojectivec2swift.net while t'was brave attempt @ conversion, didn't cut mustard

it gives

labels.text = [nsstring stringwithformat:@"%i",bags[tempvalue]]; 

as equivalent:

labels.text = "\(bags[tempvalue])" // compiler warns.. cannot assign 'text' in 'labels' 

disclosure: based on question asked here: iphone - how select collection of uilabels? ( , in end none of answers quite did me experimented way round. ) recent swift-related searches discuss not-quite-fitting approaches


edit: sake of completeness [and requested] here's whole swift code function in context

    @ibaction func acceptweight(sender: uibutton)  {     var tempvalue: int = currentweight      labels: uilabel in self.view.subviews {         if labels.tag == currentweight {           bags[tempvalue]++           labels.text = "\(bags[tempvalue])"       }    }    totalkilo = totalkilo + currentweight     self.totalkilo.text = "\(totalkilo)" } 

you making assumptions subviews uilabel. add button, break. try this:

@ibaction func acceptweight(sender: uibutton)  {     var tempvalue = currentweight      subview in self.view.subviews {         if let label = subview uilabel label.tag == currentweight {           bags[tempvalue] += 1           label.text = "\(bags[tempvalue])"       }    }    totalkilo = totalkilo + currentweight    self.totalkilo.text = "\(totalkilo)" } 

Comments