Resizing UIView based on content - iphone

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.

Related

How do I truncate a string within a string in a UILabel?

Say I have The Dark Knight Rises at 7:45pm and I need to fit that into a fixed-width UILabel (for iPhone). How would I make that truncate as "The Dark Knight Ris... at 7:45pm" rather than "The Dark Knight Rises at 7:4..."?
UILabel has this property:
#property(nonatomic) NSLineBreakMode lineBreakMode;
You enable that behaviour by setting it to NSLineBreakByTruncatingMiddle.
EDIT
I din't understand that you wanted to truncate only a part of the string.Then read this:
If you want to apply the line break mode to only a portion of the text, create a new attributed string with the desired style information and associate it with the label. If you are not using styled text, this property applies to the entire text string in the text property.
Example
So there is even a class for setting the paragraph style: NSParagraphStyle and it has also it's mutable version.
So let's say that you have a range where you want to apply that attribute:
NSRange range=NSMakeRange(i,j);
You have to create a NSMutableParagraphStyle object and set it's lineBreakMode to NSLineBreakByTruncatingMiddle.Notice that you may set also a lot of other parameters.So let's do that:
NSMutableParagraphStyle* style= [NSMutableParagraphStyle new];
style.lineBreakMode= NSLineBreakByTruncatingMiddle;
Then add that attribute for the attributedText of the label in that range.The attributedText property is a NSAttributedString, and not a NSMutableAttributedString, so you'll have to create a NSMutableAttributedString and assign it to that property:
NSMutableAttributedString* str=[[NSMutableAttributedString alloc]initWithString: self.label.text];
[str addAttribute: NSParagraphStyleAttributeName value: style range: range];
self.label.attributedText= str;
Notice that there are a lot of other properties for a NSAttributedString, check here.
You have to set the lineBreakMode. You can either do that from Interface Builder or programmatically as follows
label.lineBreakMode = NSLineBreakByTruncatingMiddle;
please note that since iOS 5 the type of such property changed from UILineBreakMode to NSLineBreakMode.
My first idea would be two labels side-by-side both with fixed width, but I'll assume you've ruled that out for some unstated reason. Alternatively, compute the truncation manually, like this ...
- (NSString *)truncatedStringFrom:(NSString *)string toFit:(UILabel *)label
atPixel:(CGFloat)pixel atPhrase:(NSString *)substring {
// truncate the part of string before substring until it fits pixel
// width in label
NSArray *components = [string componentsSeparatedByString:substring];
NSString *firstComponent = [components objectAtIndex:0];
CGSize size = [firstComponent sizeWithFont:label.font];
NSString *truncatedFirstComponent = firstComponent;
while (size.width > pixel) {
firstComponent = [firstComponent substringToIndex:[firstComponent length] - 1];
truncatedFirstComponent = [firstComponent stringByAppendingString:#"..."];
size = [truncatedFirstComponent sizeWithFont:label.font];
}
NSArray *newComponents = [NSArray arrayWithObjects:truncatedFirstComponent, [components lastObject], nil];
return [newComponents componentsJoinedByString:substring];
}
Call it like this:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 21)];
NSString *string = #"The Dark Knight Rises at 7:45pm";
NSString *substring = #"at";
CGFloat pix = 120.0;
NSString *result = [self truncatedStringFrom:string toFit:label atPixel:120.0 atPhrase:#"at"];
label.text = result;
This generates: #"The Dark Kni...at 7:45pm"

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;
}
}
}

UITableViewCell holding a UIWebViewCell with Dynamic Height and a Loading Animation

I am currently trying to nest a UIWebView (among other elements) into a custom UITableViewCell subclass.
I need to dynamically determine the size of the cell (using heightForRowAtIndexPath) but for some reason when I do it like so, the height always gets printed as 0:
UIWebView* wv = [[[UIWebView alloc] init] autorelease];
[wv loadHTMLString:body baseURL:nil];
[wv setNeedsLayout]; //I don't think these are necessary but I tried anyway.
[wv setNeedsDisplay];
CGSize wvSize = [wv sizeThatFits:webViewBounds];
NSLog(#"WVHEIGHT %f", wvSize.height); //THIS IS WHERE IT PRINTS.
CGFloat retVal = 10.0f;
retVal += 50 > wvSize.height ? 50 : wvSize.height;
retVal += 2 + 15 + 10;
return retVal;
Now, if I do that exact same calculation using the cell.webView that I have access to in cellForRowAtIndexPath, it returns a non-zero value. However, I'd really like to avoid loading an entire cell just to figure out how tall it should be...
Additionally, UIWebView is very slow at rendering text (and it is unfortunately not negotiable that I use UIWebView), so I was wondering if there's a way to tell it to display the typical Apple "rotating gear" activity icon until it has its text fully loaded and ready to render.
I would recommend hiding each UIWebView until it is done loading, and showing a loading indicator instead. I would then make a dictionary with keys that match the tags, and for each entry in the dictionary, I would store the size of the UIWebView.
Make your controller conform to the UIWebViewDelegate protocol, and use the following code:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *output = [webView stringByEvaluatingJavaScriptFromString:#"document.getElementById('this').offsetHeight;"];
[self.webViewHeights setValue:[output floatValue] forKey:[NSString stringWithFormat:#"%f", webView.tag]];
}
After that, add code to hide your loading view and display your UIWebView, then call a table reload. In your cell height method, just check the correct array element for your UIWebView height.
Edit:
It seems I left out the important part!
OK, so, to create non-visible UIWebViews, you just need to create them, but not actually add them to a view. For example, you could do something like this in your viewDidLoad method:
UIWebView *newWebView = [[UIWebView alloc] initWithFrame:newFrame];
[newWebView loadHTMLString:body baseURL:nil];
newWebView.tag = 1;
[self.webViewDictionary setObject:newWebView forKey:#"1"];
Then in your table code, say something like
NSString *tagString = [NSString stringWithFormat:#"%d", indexPath.row];
UIWebView *curWebView = [self.webViewDictionary objectForKey:tagString];
if (curWebView.loading == NO) {
CGRect newFrame = curWebView.frame;
newFrame.size.height = [self.webViewHeights objectForKey:tagString];
curWebView.frame = newFrame;
[cell addSubview:curWebView];
} else {
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorStyleGray];
[cell addSubview:activityIndicator];
}
I don't think sizeThatFits: is what you want to use.
sizeThatFits:
Asks the view to calculate and return
the size that best fits its subviews.
Your webview does not have any subviews, only HTML.
UIWebView has no init method of its own, so you probably should use initWithFrame: (from the UIView superclass) to set the size directly. You can set it to the size you want, which is the size of the tableView cell in this case.

uitableviewcell textlabel too long and push detailtextlabel out of view

When i'm using UITableViewCellStyleValue1, i got a long string of textLabel, and somehow the detailTextLabel got push out from the view.
When i shorted my textLabel text, then i can see the detailTextLabel's text.
Is there anyway to limit the width of textLabel in the above style so that it will truncate the textLabel with it's too long?
My code is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation;
//---get the letter in each section; e.g., A, B, C, etc.---
NSString *alphabet = [self.currencyNameIndex objectAtIndex:[indexPath section]];
//---get all states beginning with the letter---
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", alphabet];
self.currencyList = [self.keyCurrencyName filteredArrayUsingPredicate:predicate];
if ([self.currencyList count] > 0)
{
NSString *currencyName = [self.keyCurrencyName objectAtIndex:indexPath.row];
cell.textLabel.text = currencyName;
NSString *currencyCode = [self.valueCurrencyCode objectAtIndex:indexPath.row];
cell.detailTextLabel.text = currencyCode;
}
return cell;
}
so my currency name will be a long one on some entry.
Simplest for me was to subclass UITableViewCell and override the layoutSubviews.
Couldn't find a reliable way to calculate the positions from just the label frames so just hardcoded the accessory width for in this case a UITableViewCellStyleValue1 cell with a UITableViewCellAccessoryDisclosureIndicator accessory type.
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat detailTextLabelWidth = [self.detailTextLabel.text sizeWithFont:self.detailTextLabel.font].width;
CGRect detailTextLabelFrame = self.detailTextLabel.frame;
if (detailTextLabelFrame.size.width <= detailTextLabelWidth && detailTextLabelWidth > 0) {
detailTextLabelFrame.size.width = detailTextLabelWidth;
CGFloat accessoryWidth = (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) ? 28.0f : 35.0f;
detailTextLabelFrame.origin.x = self.frame.size.width - accessoryWidth - detailTextLabelWidth;
self.detailTextLabel.frame = detailTextLabelFrame;
CGRect textLabelFrame = self.textLabel.frame;
textLabelFrame.size.width = detailTextLabelFrame.origin.x - textLabelFrame.origin.x;
self.textLabel.frame = textLabelFrame;
}
}
#Jhaliya #lucas
cell.textLabel.numberOfLines = 3; // set the numberOfLines
cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation;
see here: Custom UITableViewCell. Failed to apply UILineBreakModeTailTruncation
I ran into a similar problem when trying to use "Right Detail" in UITableView; the right detail's built in title label was clobbering my subtitle label.
Eventually I gave up on the "Right Detail" in favor of my own custom one (using swift and autolayout):
I created my own simple class that inherited from the UITableViewCell:
class TransactionCell: UITableViewCell
{
}
I set my prototype cell use that custom class by setting the "Style" field to "Custom" on the "Table View Cell" Menu and by adding "TransactionCell" to the "Class" field of the "Custom Class" menu. These menus are available when you select the prototype cell in the storyboard.
I added two labels to my prototype cell and connected them to my custom class by right click dragging from my labels to my class (Oddly, I had to clean my build before it would let me do this):
class TransactionCell: UITableViewCell{
#IBOutlet weak var detailsLabel: UILabel!
#IBOutlet weak var amountLabel: UILabel!
}
I added new constraints to my labels, taking advantage of swift's autolayout features (You will need to set these to match your own requirements; see a tutorial on autolayout if you are stuck)
...and set the "Lines" and "Line Breaks" fields in the respective "Label" menus so that the spacing between labels would be even and so that my details label could flex to multiple lines.
It worked for me, allowing me to have the flexibility of different amounts of multiple lines in a UITableView in swift per cell, while formatting the word wrapping so that it looked nice and even, like I would have expected the "Right Detail" to do automatically.
I had the same problem and had to create a UITableViewCell subclass. It's easier to do that than I thought:
Basically, just make a new file, that is a subclass of UITableViewCell
Add the labels and synthesize them:
// in the .h file
#property (nonatomic, weak) IBOutlet UILabel *textLabel;
#property (nonatomic, weak) IBOutlet UILabel *detailTextLabel;
// in the .m file
#synthesize textLabel, detailTextLabel;
In the StoryBoard, set your class as the cell's class, make the Style "Custom" and add two labels in the cell to look exactly as you want (I made them look the same as the default: http://cl.ly/J7z3)
The most important part is to make sure you connect the labels to the cell
You need to control-click from the Cell to the label in the Document outline. Here's a picture of what it looks like: http://cl.ly/J7BP
What helped me to understand how to create custom cell, dynamic cells, and static cells is this youtube video: http://www.youtube.com/watch?v=fnzkcV_XUw8
Once you do that, you should be all set. Good luck!
Swift version supporting the latest iOS (12):
override func layoutSubviews() {
super.layoutSubviews()
guard let detailWidth = detailTextLabel?.intrinsicContentSize.width, var detailFrame = detailTextLabel?.frame else {
return
}
let padding = layoutMargins.right
if (detailFrame.size.width <= detailWidth) && (detailWidth > 0) {
detailFrame.size.width = detailWidth
detailFrame.origin.x = frame.size.width - detailWidth - padding
detailTextLabel?.frame = detailFrame
var textLabelFrame = textLabel!.frame
textLabelFrame.size.width = detailFrame.origin.x - textLabelFrame.origin.x - padding
textLabel?.frame = textLabelFrame
}
}
Adjust the frame of the view: textLabel
CGRect aFrame = cell.textLabel.frame;
aFrame.size.width = 100; // for example
cell.textLabel.frame = aFrame;
Updated Gosoftworks Development`s answer.
Swift 3
class BaseTableViewCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
guard let tl = textLabel, let dl = detailTextLabel else { return }
if (tl.frame.maxX > dl.frame.minX) {
tl.frame.size.width = dl.frame.minX - tl.frame.minX - 5
}
}
}
Create a custom UITableViewCell with a UILabel in it that you can control however you want, or truncate the text that you assign to the base-class textLabel to fit the space that you have.
It's not perfect, but I have used the text-truncation technique in places where a custom cell is overkill (ex. when the only issue was fitting the text in) using an NSString category with a method similar to the following:
- (NSString *)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font
{
NSString *result = [NSString stringWithString:self];
while ([result sizeWithFont:font].width > width)
{
result = [result stringByReplacingOccurrencesOfString:#"..." withString:[NSString string]];
result = [[result substringToIndex:([result length] - 1)] stringByAppendingString:#"..."];
}
return result;
}
Probably not 'optimized' but it works for simple scenarios.
1st: set line break mode
textLabel.lineBreakMode = NSLineBreakByTruncatingTail;
2nd: set texLabel frame width you want (e.g. 200)
CGRect textFrame = self.textLabel.frame;
CGRect newTextFrame = CGRectMake(textFrame.origin.x, textFrame.origin.y, 200, textFrame.size.height);
self.textLabel.frame = newTextFrame;
It works!! But i just changed Christopher King`s code:
- (NSString *)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font :(NSString*) result
{
while ([result sizeWithFont:font].width > width)
{
result = [result stringByReplacingOccurrencesOfString:#"..." withString:[NSString string]];
result = [[result substringToIndex:([result length] - 1)] stringByAppendingString:#"..."];
}
return result;
}
and usage:
NSString* text = #"bla bla bla some long text bla bla";
text = [self stringByTruncatingToWidth:cell.frame.size.width-70.0 withFont:[UIFont systemFontOfSize:17] :text];
cell.textLabel.text = text;
I've struggled with this a bunch and found a pretty simple answer. My textLabel was on the left and would push out the detailText on the right to the point you couldn't see it at all sometimes.
My solution, change the Table View Cell style to Subtitle from Left Detail or Right Detail. This solution works if you don't mind your detailText being below instead of on the right or left.
If you are having issues with the height of the row, you can adjust that using the code below in viewDidLoad.
self.tableView.estimatedRowHeight = 500 // set this as high as you might need, although I haven't tested alternatives
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.reloadData()
Use the UILabel lineBreakMode property to restrict your text within the width of your UILabel
#property(nonatomic) UILineBreakMode lineBreakMode
Use it as below.
myLabel.lineBreakMode = UILineBreakModeTailTruncation;
Here is the list of values which could be used with lineBreakMode.
http://developer.apple.com/library/ios/#documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html#//apple_ref/doc/c_ref/UILineBreakMode
EDITED:
Set the width of your UILabel as per your requirment
eg.
myLabel.frame.size.width = 320;

Loop through labels iPhone SDK

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];
}