XCode - Dynamically created labels, when i change the text it changes it for the last one only

前端 未结 2 474
自闭症患者
自闭症患者 2021-01-29 14:30

So i have a bunch of dynamically loaded labels..

Each of them has the same name because there is no telling how many there will be..

I have another method (not t

相关标签:
2条回答
  • 2021-01-29 14:48

    Okay since you dont have any code to show i guess i have to speculate.

    What i understood is that you are creating Dynamic UILabels in ur code and you want to access them. Since you have same name for all the UILabels you might me loosing the previous UILabel when every time you create a new UILabel. So in order to keep track of how many UILabel you created you must add them in an Array. Declare an NSMutableArray in your viewController.h file and make sure in the viewDidLoad u allocate it like

    arrForLabels = [[NSMutableArray alloc]init];
    

    Since it is an NSMutableArray you can add object to it.

    So when u create a UILabel make sure you add the same UILabel in the Array as well for Instance

    [arrForLabels addObject:yourLabel];
    

    you can try to NSLog your Array to see its content.

    Now all youu got to do is to Create a weak link like that

    UILabel *tempLabel = [arrForLabels objectAtIndex:1];
    

    now tempLabel will be the UILabel to change text

    tempLabel.text = @"My New Text";
    

    It will work fine. Feel free to ask for any issues in it.

    0 讨论(0)
  • 2021-01-29 14:58

    self.myLabel cannot be connected to multiple labels, so it will contain the reference of last created label, you will have to create new label every time, and you can't track them by class properties, you have to access label by their tag.

    you can set tag for each label, below is sample code,

     for(int i=0; i< numberOfLabels; i++)
    {
        UILabel *label = [[UILabel alloc] init];
        label.tag = i; // do not use tag 0 here.. u can use i+1, or i+100.. something like this.
        [self.view addSubview:label];
    }
    

    to access labels,

    UILabel *label = (UILabel*)[self.view viewWithTag: labelTag];
    
    0 讨论(0)
提交回复
热议问题