iphone - Adding UILabels Dynamically in a Loop -
i looking function or loop prototype add uilabels view on iphone. reason won't know in advance how many labels need add, need added dynamically.
my pseudo code follows. idea each label given string , placed in next screen, hence +self.view.frame.size.width statement. paging etc work perfectly, problem labels appear ending on second screen i.e. label 3 appears on top of label 2. issue appear referencing altlabel, , such once move second position, referencing position , never moving once there.
i can use 'count' variable multiple screen width, if that, every time update label text, overwrite previous.
int count = 0; int maxnumber = 10; while(count < maxnumber) { //add label uilabel *altlabel; //declare label if (count > 0) { //move label altlabel = [[uilabel alloc] initwithframe:cgrectmake(cgrectgetminx(altlabel.frame)+self.view.frame.size.width,10,300,25)]; altlabel.text = [nsstring stringwithformat:@"%@ %@ (%d)", _name,_age, class+count]; } else { altlabel = [[uilabel alloc] initwithframe:cgrectmake(10,10,300,25)]; altlabel.text = [nsstring stringwithformat:@"%@ %@ (%d)", _name,_age, class]; } altlabel.textcolor = [uicolor greencolor]; [altlabel sizetofit]; [_scrollview addsubview:altlabel]; count++; }
the problem line:
uilabel *altlabel; // declare label if (count > 0) { //move label altlabel = [[uilabel alloc] initwithframe:cgrectmake(cgrectgetminx(altlabel.frame)+self.view.frame.size.width,10,300,25)]; altlabel.text = [nsstring stringwithformat:@"%@ %@ (%d)", _name,_age, class+count]; }
you setting frame using altlabel.frame, there altlabel not setted up: redeclared on first line uilabel *altlabel.
with code every label first have same frame. try this:
int count = 0; int maxnumber = 10; cgrect rect; while(count < maxnumber) { // add label uilabel *altlabel; // declare label if (count > 0) { //move label altlabel = [[uilabel alloc] initwithframe:cgrectmake(cgrectgetminx(rect.frame)+self.view.frame.size.width*count, 10, 300, 25)]; altlabel.text = [nsstring stringwithformat:@"%@ %@ (%d)", _name,_age, class+count]; } else { altlabel = [[uilabel alloc] initwithframe:cgrectmake(10, 10, 300, 25)]; altlabel.text = [nsstring stringwithformat:@"%@ %@ (%d)", _name,_age, class]; } rect = altlabel.frame; altlabel.textcolor = [uicolor greencolor]; [altlabel sizetofit]; [_scrollview addsubview:altlabel]; count++; }
now frame of new label saved in temporary var (cgrect frame) , can use it.
Comments
Post a Comment