UndefinedReference
UndefinedReference

Reputation: 1253

Setting UILabel Text Multiple Times Within A Loop

I'm fooling around in XCode, trying to learn a little about the iOS SDK and Objective-C.

I have this for loop below, and it should print out several values to the screen (depending on the amount of months chosen), but instead, it's only printing out the final value.

Can anybody point out why?

Thanks a bunch, in advance!

for (int i = 1; i <= myMonthsDouble; i++)
{
    myPaymentAmount = (myBalanceDouble/10) + myInterestDouble;
    myBalanceDouble -= myPaymentAmount;
    //convert myPaymentAmount double into string named myPaymentAmountString
    NSString *myPaymentAmountString = [NSString stringWithFormat:@"%f", myPaymentAmount];
    NSString *paymentInformation = [[NSString alloc] initWithFormat:@"%@ months, %@ per month.", monthsString, myPaymentAmountString];
    myInterestDouble = (myBalanceDouble * (myInterestDouble/100))/12;
    self.label.text = paymentInformation;
}

Upvotes: 0

Views: 399

Answers (1)

Jsdodgers
Jsdodgers

Reputation: 5312

It is only printing the last value to the screen because you only have one label. Each time you get to the end of the loop, you are setting that label's text which is overriding the last value. If you want to print all of them to the screen, you will need to have either multiple labels or you will have to append the strings together and put them in either a label or a UITextView that is formatted so that they can all be seen (most likely a text view but it can be done with a label.)

One example of doing this would be:

label.text = [label.text stringByAppendingString:newString];
numLines++; //this starts at 0;

and then at the end:

label.numberOfLines = numLines;

Upvotes: 3

Related Questions