Loop through labels iPhone SDK - iphone

Ok I have 8 labels and I want to loop through them but am having no luck.
This is what I have tried.
for (int i; i = 0; i < 10; i++)
{
double va = [varible1.text doubleValue] + i;
int j = 0 + I
label(j).text= [[NSString alloc]initWithFormat:#"%2.1f", va];
}
This errors out. My labels are named like this label0, label1, label2
Any help would be appreciated.

label(j) is NOT equivalent to label0, label1, etc.
You should create an NSArray of labels, then you can access them with [arrayOfLabels objectAtIndex:j]. If you're not sure what this means, please read the documentation about NSArray...

You should maybe add all your labels to a C array, probably in -viewDidLoad
UILabel* labels[] = { label0, label1, label2, ... };
(not entirely sure about the syntax)
and then access them like
labels[i].text = ...
By the way, I think you're leaking memory here:
labels[i].text = [[NSString alloc]initWithFormat:#"%2.1f", va];
initWithFormat: will return a string with a retain count of 1. labels[i].text will retain that value again. You should release the string after setting the label's text. I'd probably just autorelease it here:
labels[i].text = [[[NSString alloc]initWithFormat:#"%2.1f", va] autorelease];
or use stringWithFormat (which returns an autoreleased string):
labels[i].text = [NSString stringWithFormat:#"%2.1f", va];

for (UILabel *lbl in self.view.subviews)
{
[lbl setFont:[UIFont fontWithName:#"AppleGothic" size:22]];
}
it will change all the labels in your ViewController by just giving tags to labels.

If you cannot or do not want to put your labels in an array, you could iterate through the UIViews using the tag field as an index. You store the index numbers in them (either through IB or programatically) and then get each label using: (UIView *)viewWithTag:(NSInteger)tag.
See below (set theView to the view your labels reside in):
for (int i; i = 0; i < 10; i++)
{
double va = [varible1.text doubleValue] + i;
UILabel * label = [theView viewWithTag: i];
label.text= [[NSString alloc]initWithFormat:#"%2.1f", va];
}

Related

Iterate through controls in iPhone

i have 9 IBOutlets for imageView named imageView1,imageView2,....
i have to assign first object of array to imageView1 & second object to imageView2,.....
Now my question is- is there any way to iterate through the property name
example-
for(int i=0;i<[randomizedArray count];i++)
{
NSString *imageViewName=[NSString stringWithFormat:#"%#%i",#"imageView",i];
imageViewName.image=[appDelegate.splittedImageArray ObjectAtIndex:i];
}
that means it automatically assign value as
imageView1.image=[appDelegate.splittedImageArray ObjectAtIndex:i];
imageView2.image=[appDelegate.splittedImageArray ObjectAtIndex:i];
The closest you could get to something like that without changing the IBOutlets would be this:
NSArray *imageViews = #[imageView1,imageView2,imageView3, ...];
for(int i=0; i<[randomizedArray count]; i++) {
[[imageViews objectAtIndex:i] setImage:[appDelegate.splittedImageArray objectAtIndex:i]];
}
But there is a better solution - IBOutletCollection
You can define a property like this:
#property (nonatomic, retain) IBOutletCollection(UIImageView) NSArray *imageViews;
And connect all of your imageViews like so:
Then you will have an array containing all of your UIImageViews, and you can use the above code without having to declare such an array manually...
dont think it complexly. This is very simple. put tag for the imageviews like tag 1 for imageview1, 2 for imageview2 and so on. Then run a for loop and pick the object and assign to the array. Thats all.
Like assume you put tag from 1 to 7 (don't put duplicate tag or 0 for any of your views)
NSMutableArray *arr = [[NSMutableArray alloc] init];
for(int ii = 1; ii<=7; ii++){
UIImageView *imgView = (UIImageView *)[self.view viewWithTag:ii];
[arr addObject:imgView];
}
yourArray = arr;
[arr release];//if your array is a property otherwise no need to release.
Hope this will help you.
use NSClassFromString
for(int i=0;i<[randomizedArray count];i++)
{
NSString *imageViewName=[NSString stringWithFormat:#"%#%i",#"imageView",i];
Class theClass = NSClassFromString(imageViewName);
theClass.image=[appDelegate.splittedImageArray ObjectAtIndex:i];
}
One way I have used to do this . Created the array of IBOutlets so you can iterate through it and assign the corresponding image.
for(int i=0;i<[randomizedArray count];i++)
{
UIImageView *imageView=[imageOutlets objectAtIndex:i];
UIImage *image=[images objectAtIndex:i];
imageView.image=image;
}

UILabel - Display ... when text length crosses certain length

I have placed UILabel in my application, in that I want to display the text with .... once the length of the text exceeds the certain count.
Because if the text goes longer, it gives the design issue.
Please let know which function to use.
Try this
yourLabel.lineBreakMode=UILineBreakModeTailTruncation;
If you are adding your UILabel from interface builder you can do it directly. Select you UILabel and in the Utilities column in Attriubtes Inspector=> Label section=> Line Breaks set Truncate Tail
Try this will helpful for you.
NSString *string=YourString;
int size=[YourString length];
if (size>21)
{
NSMutableString *string1 = [[NSMutableString alloc]init];
char c;
for(int index = 0;index <20 ;index++)
{
c =[string characterAtIndex:index];
[string1 appendFormat:#"%c",c];
}
[string1 appendFormat:#"..."];
string=string1;
}
Add "string" on your UILable.
#define EXCEEDED_LENGTH 8
- (NSString *) checkStringLength:(NSString *)str
{
if(str.length >= EXCEEDED_LENGTH)
{
return [NSString stringWithFormat:#"%#...",[str subStringToIndex:EXCEEDED_LENGTH-1]];
}
return str;
}
yourLabel.text = [self checkStringLength:#"Hello World !!"];
Output like Hello Wo... For better output you can trim whitespaces before pass string to function.
From the information you shared I think the autoshrink and linebreakermode may be the root cause.IT is the property which tries to show the contents in the specified frame which will decrease and adjust the font size
2 ways to sove the issue
adjust the property according to requirement
Increase the framesize of label(programmatically by finding size)
also look on the edge insets
Either you can make UILable size(length/width) Dynamic,
Or
You can UITextView with edit disable so if there will be long text it will be scrollable.
CGSize constraint = CGSizeMake(690.0, 2000.0);
CGSize size_txt_overview1 = [[headItemArray objectAtIndex:k] sizeWithFont:[UIFont fontWithName:#"Helvetica" size:18] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
UILabel *lbl_headitem = [[UILabel alloc]initWithFrame:CGRectMake(3,h, 690, size_txt_overview1.height)];
lbl_headitem.numberOfLines=0;
Please set your UILabel width and height in CGSize constraint. Best way.. and it worked for me.
This is a method for a Category of UILabel
-(void)setTruncatedTextWithDotsIfNeeded:(NSString *)text
{
float fullTextWidth = [text sizeWithFont:self.font].width;
float labelWidth = self.frame.size.width;
if(fullTextWidth<=labelWidth){
[self setText:text];
return;
}
NSString *dots = #"…";
float dotsWidth = [dots sizeWithFont:self.font].width;
NSRange fullRange = [text rangeOfString:text];
for(int i = fullRange.length; i >= fullRange.location; i--){
NSRange currentRange;
currentRange.location = 0;
currentRange.length = i;
NSString *partialText = [text substringWithRange:currentRange];
float partialTextWidth = [partialText sizeWithFont:self.font].width;
if(partialTextWidth + dotsWidth <= labelWidth){
[self setText:[NSString stringWithFormat:#"%#...",partialText]];
return;
}
}
}

access string names using variables in FOR statement

is is possible to access objects using variables in a FOR statement?
Say i have declared:
UIImageView *UIImageView0;
UIImageView *UIImageView1;
UIImageView *UIImageView2;
and i have 3 objects in an array and i call a FOR statement if x in the array is equal to 2 i want it to add the value of x to the UIImageView name like UIImageView1 etc
I have tried:
for (int x=0; x<[theArray count]; x++) {
UIImageView[x].image = etc....
}
but it gives me a error on UIImageView[x]
subscript requires size of interface 'UIImageView'
any ideas? or is it even possible with a UIImageView?
Thanks
You don't have three elements in an array, though; you have three independent variables with similar names. If you created an actual array, containing the values of the three variables, then you could use the for loop -- and in fact, the syntax would be just as you've shown (using the actual name of the array variable, of course.)
You could say
UIImageView * views[3] = {UIImageView0, UIImageView1, UIImageView2};
and then use, for example, views[i].image in your loop.
In order to put your UIImageView into an array you need to create an instance NSMutableArray (for instance)
The above code does not show any array, instead you have three ivars
UIImageView *UIImageView0;
UIImageView *UIImageView1;
UIImageView *UIImageView2;
and to access those you would use the name, not an array.
If you however put them into an NSMutableArray you can access them using
NSMutableArray array = [[NSMutableArray alloc]
initWithObjects:UIImageView0, UIImageView1, UIImageView2, nil];
[array objectAtIndex:i ]; // where i is 0,1 or 2
...
[array release];
You can put your UIImageView to another array, and get the UIImageView from that array.
NSArray *imagesArray = #[imageView0, ...]
for(size_t i = 0; i<theArray.count; i++)
{
UIImageView *imageView = [imagesArray objectAtIndex:i];
}
Or you can use the "tag" property of UIView like:
UIImageView *image0 = ...;
image0.tag = 100; //or 0 or something else
[self.view addSubview:image0];
And then get the UIImageView by tag in your FOR statement:
for(size_t i = 0; i<theArray.count; i++)
{
UIImageView *imageView = [self.view viewWithTag:100+i];
}

Resizing UIView based on content

I have a view with a lot of labels being populated with parsed XML. That view is within a UIScrollView. Some of the XML is too long for the labels. I'm resizing the labels based on the XML content. When the labels are re sized, they overlap the subsequent labels because my UIView (that is within the UIScrollView) isn't being re sized. I've been scouring the internet for hours trying to find an answer to this, but everything that I've tried hasn't achieved what I'm looking for. Any help would be greatly appreciated.
This is my populateLabels method.
-(void) populateLabels {
NSString *noInfo = (#"No Information Available");
lblCgName.text = _Campground.campground;
NSString *cgLoc = _Campground.street1;
NSString *cgCity = _Campground.city;
NSString *cgState = _Campground.state1;
NSString *cgCountry = _Campground.country;
NSString *cgZipPostal = _Campground.zipPostal;
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgCity];
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgState];
cgLoc = [[cgLoc stringByAppendingString:#", "] stringByAppendingString:cgCountry];
cgLoc = [[cgLoc stringByAppendingString:#" "] stringByAppendingString:cgZipPostal];
lblCgLoc.text = cgLoc;
double dRate = [_Campground.regRate1 doubleValue];
double dRate2 = [_Campground.regRate2 doubleValue];
NSString *rate = [[NSString alloc] initWithFormat:#"$%0.2f",dRate];
NSString *rate2 = [[NSString alloc] initWithFormat:#"$%0.2f",dRate2];
if ([rate2 isEqualToString:#"$0.00"]) {
lblRate.text = rate;
} else {
rate = [[rate stringByAppendingString:#" - "] stringByAppendingString:rate2];
lblRate.text = rate;
}
double dPaRate = [_Campground.paRate1 doubleValue];
double dPaRate2 = [_Campground.paRate2 doubleValue];
NSString *paRate = [[NSString alloc] initWithFormat:#"$%0.2f",dPaRate];
NSString *paRate2 = [[NSString alloc] initWithFormat:#"$%0.2f",dPaRate2];
if ([paRate2 isEqualToString:#"$0.00"]) {
lblPaRate.text = paRate;
} else {
paRate = [[paRate stringByAppendingString:#" - "] stringByAppendingString:paRate2];
lblPaRate.text = paRate;
}
lblLocal1.text = _Campground.localPhone1;
lblLocal2.text = _Campground.localPhone2;
lblTollFree.text = _Campground.tollFree;
lblFax.text = _Campground.fax;
lblEmail.text = _Campground.email;
lblWebsite.text = _Campground.website;
NSString *gps = _Campground.latitude;
NSString *longitude = _Campground.longitude;
gps = [[gps stringByAppendingString:#", "] stringByAppendingString:longitude];
lblGps.text = gps;
lblHighlights.text = _Campground.highlights;
lblHighlights.lineBreakMode = UILineBreakModeWordWrap;
lblHighlights.numberOfLines = 0;
//label resizing
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [_Campground.highlights sizeWithFont:lblHighlights.font
constrainedToSize:maximumLabelSize
lineBreakMode:lblHighlights.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = lblHighlights.frame;
newFrame.size.height = expectedLabelSize.height;
lblHighlights.frame = newFrame;
lblTents.text = _Campground.tents;
lblNotes.text = _Campground.notes;
lblDirections.text = _Campground.directions;
lblRentals.text = _Campground.rentals;
}
Where is the - (void) populateLabels method located? If it's in a view controller, you should have easy access to the view that needs to be resized. Alternatively, if the labels (which look to already be created) have been added to the view that needs to be resized, then you can access their superview. You've already got size you need, just set set the superview's frame size at the end of the method.
If you're trying to find the size of each label first based on the string content, you'll want to use the NSString method: -sizeWithFont. There are several variations of this that allow you to specify constraints:
Computing Metrics for a Single Line of Text
– sizeWithFont:
– sizeWithFont:forWidth:lineBreakMode:
– sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:
Computing Metrics for Multiple Lines of Text
– sizeWithFont:constrainedToSize:
– sizeWithFont:constrainedToSize:lineBreakMode:
Remember that UILables only show 1 line of text. Also keep in mind that this will return the size that the string will take up. Views like UILabels and UITextViews tend to add padding, so you may need to account for that when calculating the height. After you've calculated the height and placed each label, you should then know the size the superView will need to be and set it appropriately. Also, if you don't know which label will be last/lowest/furthest down in the view (the size of the superView should be the origin.y + the size.height of the last view) you can do something like this:
CGFloat totalHeight = 0.0f;
for (UIView *view in superView.subviews)
if (totalHeight < view.frame.origin.y + view.frame.size.height) totalHeight = view.frame.origin.y + view.frame.size.height;
This will give you the height of the superview if you don't already know it (and you can do the same thing for width if need be).
Do you really need to use a bunch of labels?
It seems you need to use UITextView or UIScrollView.
The general method to resize a UIView based on its subviews is sizeToFit
This method resizes your UIView automatically.
If you wanted to constrain the size, you'll need to use sizeThatFits: This method does not resize your UIView automatically, rather it returns the size.
Just a side note: These two methods only factor in subviews so not drawings nor Core Text.

iPhone OS: Using an NSString variable to specify a property or ivar

I have a program that I want to either hide or show certain UIbuttons depending on certain variables and all the buttons are named incrementally like 'button1, button2, button3.'
So I want to iterate through the buttons but I don't know how to address the button in an assignment statement using an nsstring as a variable inside a dot notation assignment, such as:
for (int i = 1; i < weekday; i++) {
int buttonIncrement = 0;
NSString *tempString = [[NSString alloc] initWithFormat:
#"calbutton%i", buttonIncrement];
self.tempString.hidden = YES;
}
The "tempString" part of the assignment I want to tell it to insert "calbuttonx" where x is the button number.
Can you do this somehow? if so please explain.
Use an array!
If you can't use an array, you can reference to a property by string with Key-Value Coding (KVC):
UIButton* button = [self valueForKey:tempString];
button.hidden = YES;
You can also assign a tag to each button in IB and get the button associated with the tag using
- (UIView *)viewWithTag:(NSInteger)tag
as defined on class UIView, for example:
for( int k = 0; k < 5; ++k ) {
id subview = [self.view viewWithTag: k];
if( subview ) {
...
}
}