Calculate input from textfield in a loop - xcode

How can I calculate a textfield in a loop? I have a textfield in a loop and I want to calculate the input in another textfield.
x = 36; y = 0; w = 36 h = 25 ;
moretext = 0 ;
for (moretext=0; moretext<5; moretext ++) {
textFiled1 = [[UITextField alloc]initWithFrame:CGRectMake(x, y, w, h)];
textFiled1.textAlignment = NSTextAlignmentCenter;
textFiled1.backgroundColor = [UIColor clearColor];
textFiled1.font = [UIFont fontWithName:#"Helvetica " size:(8)];
x+=36 ;
[self.view addSubview:textFiled1];
}
I want to have the TOTAL for the textfield1 loop input showing in textfield2
textFiled2 = [[UITextField alloc]initWithFrame:CGRectMake(180, 0, 36, 25)];
textFiled2.textAlignment = NSTextAlignmentCenter;
textFiled2.backgroundColor = [UIColor clearColor];
textFiled2.font = [UIFont fontWithName:#"Helvetica " size:(8)];
[self.view addSubview:textFiled2];

Implementing the UITextFieldDelegate protocol you can get updates from the UITextField as people type. textFieldDidEndEditing: will tell you when someone is done editing a textfield as well.
See: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

May be you need to revise the code:
At the time of allocating multiple UITextField objects, you need to store these in some array like this.
myArray = [[NSMutableArray alloc]init];
UITextField *textFiled1;
int moretext = 0 ;
for (moretext=0; moretext<5; moretext ++, y=y+50) {
textFiled1 = [[UITextField alloc]initWithFrame:CGRectMake(x, y, w, h)];
textFiled1.textAlignment = NSTextAlignmentCenter;
textFiled1.backgroundColor = [UIColor blueColor];
textFiled1.font = [UIFont fontWithName:#"Helvetica " size:(8)];
textFiled1.text = [NSString stringWithFormat:#"%d",y];
//x+=36 ;
[myArray addObject:textFiled1];
[self.view addSubview:textFiled1];
NSLog(#"view Did Load called");
}
Later to do the total you need to traverse through array and extract the text field value and accumulate in some variable like this.
- (int) calc {
int total=0;
int counter;
for (counter=0; counter<5; counter ++) {
UITextField *field1 = [myArray objectAtIndex:counter];
total = total + [field1.text intValue];
NSLog(#"value: %d",[field1.text intValue]);
}
return total;
}

Related

Xcode UI on background thread to render image

I'm rendering an image with text for one of my apps and has a noticeable impact on UI performance (can be as big as ~1 second freeze), so I am doing it on a background thread. Since the image has text, using UILabels and other UIViews makes it easy to lay everything out, and I render the view containing everything to an image.
However, I get a warning from Xcode saying that it's not allowed on the background thread because it uses UIKit. Why am I not allowed to call UIKit on the background thread even though my use case is completely self-contained and isolated from any rendering onscreen?
To help the code below make more sense, it draws an image that is a listing of several items, each of which consists of two small square images and the name of the item all in a row. The list can have several columns. The code has been tweaked slightly (mostly variable names) to avoid showing proprietary code, but does the same job.
My code:
NSArray<MyItem*>* items; // These are the items that I'm drawing. They
// get set before the following code is called.
// Processing code:
const CGFloat TITLE_FONT_SIZE = 50; // font size of the title
const CGFloat ITEM_FONT_SIZE = 25; // font size of the item names
const int OUTER_PADDING = 60; // padding from the edge of the image to the main content
const int ROW_PADDING = 13; // padding between rows
const int COL_PADDING = 100; // padding between columns
const int PADDING = 20; // padding between content items in a row
const int BOX_SIZE = 25; // how high/wide each image is
const int ROW_HEIGHT = BOX_SIZE; // pixel height of a line
const int COL_WIDTH = 500; // pixel width of a column (image1, image2, and name)
// compute the dimensions of the image
UILabel* titleLabel = [[UILabel alloc] init];
titleLabel.font = [UIFont systemFontOfSize:TITLE_FONT_SIZE];
titleLabel.text = #"My image";
[titleLabel sizeToFit];
titleLabel.frame = CGRectMake(OUTER_PADDING, OUTER_PADDING / 2, titleLabel.frame.size.width, titleLabel.frame.size.height);
const int MIN_NUM_COLS = 1 + ((titleLabel.frame.size.width - COL_WIDTH) / (COL_WIDTH + COL_PADDING));
const int NORMAL_NUM_COLS = (int)ceil(sqrt([items count] / (COL_WIDTH / (ROW_HEIGHT))));
const int NUM_COLS = (MIN_NUM_COLS > NORMAL_NUM_COLS ? MIN_NUM_COLS : NORMAL_NUM_COLS);
const int NUM_ROWS = (int)ceil([items count] / (float)NUM_COLS);
const int NUM_OVERFLOW_ROWS = [items count] % NUM_ROWS;
const int titleWidth = titleLabel.frame.size.width;
const int defaultWidth = (NUM_COLS * (COL_WIDTH + COL_PADDING)) - COL_PADDING;
const int pixelWidth = (2 * OUTER_PADDING) + (titleWidth > defaultWidth ? titleWidth : defaultWidth);
const int pixelHeight = (2 * OUTER_PADDING) + (TITLE_FONT_SIZE + PADDING) + (NUM_ROWS * (ROW_HEIGHT + ROW_PADDING)) - ROW_PADDING;
const int nbytes = 4 * pixelHeight * pixelWidth;
byte* data = (byte*)malloc(sizeof(byte) * nbytes);
memset(data, 255, nbytes);
CGContextRef context = CGBitmapContextCreate(data, pixelWidth, pixelHeight, 8, 4 * pixelWidth, CGColorSpaceCreateDeviceRGB(), kCGBitmapByteOrderDefault | kCGImageAlphaNoneSkipLast);
// --------------------------------------------------
// create a view heirarchy and then draw to our context
UIView* mainView = [[UIView alloc] init];
[mainView addSubview:titleLabel];
// setup all the views
int keyIndex = 0;
CGFloat x = OUTER_PADDING;
CGFloat starty = titleLabel.frame.origin.y + titleLabel.frame.size.height + PADDING;
for (int col = 0; col < NUM_COLS; col++)
{
int nrows = (col == NUM_COLS + 1 ? NUM_OVERFLOW_ROWS : NUM_ROWS);
CGFloat y = starty;
for (int row = 0; (row < nrows) && (keyIndex < [items count]); row++)
{
CGFloat tempx = x;
MyItem* item = [items objectAtIndex:keyIndex];
UIImageView* imageview1 = [[UIImageView alloc] initWithImage:item.image1];
imageview1.frame = CGRectMake(tempx, y, BOX_SIZE, BOX_SIZE);
[mainView addSubview:imageview1];
tempx += BOX_SIZE + PADDING;
UIImageView* imageview2 = [[UIImageView alloc] initWithImage:item.imageview2];
imageview2.frame = CGRectMake(tempx, y, BOX_SIZE, BOX_SIZE);
[mainView addSubview:imageview2];
tempx += BOX_SIZE + PADDING;
UILabel* label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:ITEM_FONT_SIZE];
label.text = item.name;
[label sizeToFit];
label.center = CGPointMake(tempx + (label.frame.size.width / 2), imageview2.center.y);
[mainView addSubview:label];
y += ROW_HEIGHT + ROW_PADDING;
keyIndex++;
}
x += COL_WIDTH + COL_PADDING;
}
// --------------------------------------------------
// draw everything to actually generate the image
CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0, -1, 0, pixelHeight));
[mainView.layer renderInContext:context];
CGImageRef cgimage = CGBitmapContextCreateImage(context);
myCoolImage = [UIImage imageWithCGImage:cgimage];
CGImageRelease(cgimage);
CGContextRelease(context);
free(data);
As we've established in comments, what you're doing is both illegitimate and slow.
Arranging and sizing UILabel and UIImageView objects is slow, and calling
CALayer renderInContext is really slow.
And it isn't how you draw.
Everything you're doing has its analogue in the actual drawing world (Quartz 2D), and if you did it that way, not only would it be legal in the background, it probably wouldn't even need to be in the background because it would be so much faster. So:
Every place you use a UILabel, you can achieve exactly the same effect by using NSAttributedString draw... commands.
Every place you use a UIImageView, you can achieve exactly the same effect by using UIImage draw... commands.
Any of us who does any extensive drawing has learned to create structured layouts of the type you're making by using actual drawing code, and now is your chance to learn to do it too.

Core Plot not displaying labels (but it displays the graph and axes fine)

I am trying to draw a graph on my OS X app and I've successfully drawn the graph and the axes:
The data (looking at the trend) and the y-axis ticks seem to be normal. But as seen above, there are no labels on either axes and there are also no ticks at the X axis.
Here is my code:
graph = [[CPTXYGraph alloc] initWithFrame:self.mainGraph.bounds];
graph.plotAreaFrame.paddingLeft = 50;
graph.plotAreaFrame.paddingBottom = 60;
graph.plotAreaFrame.paddingTop = 10;
graph.plotAreaFrame.paddingRight = 16;
self.mainGraph.hostedGraph = graph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace*)graph.defaultPlotSpace;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterNoStyle;
NSTimeInterval oneDay = 60 * 60 * 24;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterShortStyle;
CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
timeFormatter.multiplier = #(oneDay);
NSDate *refDate = [graphDates firstObject];
timeFormatter.referenceDate = refDate;
CPTXYAxisSet *axisSet = (id)graph.axisSet;
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor grayColor];
lineStyle.lineWidth = 1.0f;
axisSet.yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0];
axisSet.yAxis.title = #"Followers";
axisSet.yAxis.titleOffset = 0;
axisSet.yAxis.majorIntervalLength = CPTDecimalFromInt(1000);
axisSet.yAxis.minorTicksPerInterval = 9;
axisSet.yAxis.majorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLineStyle = lineStyle;
axisSet.yAxis.minorTickLength = 4;
axisSet.yAxis.majorTickLength = 10;
axisSet.yAxis.tickDirection = CPTSignNone;
axisSet.yAxis.labelFormatter = numberFormatter;
axisSet.xAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:0];
axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(oneDay * 7);
axisSet.xAxis.minorTicksPerInterval = 6;
axisSet.xAxis.majorTickLineStyle = lineStyle;
axisSet.xAxis.minorTickLineStyle = lineStyle;
axisSet.xAxis.labelFormatter = timeFormatter;
axisSet.xAxis.labelRotation = M_PI / 4;
axisSet.xAxis.majorTickLength = 10;
I've also tried assigning labeling policies, but no avail (best I could get was also losing my Y-axis ticks too).
And on data refresh (including the initial load), after this code:
graphMax = followers * 1.1;
graphMin = 0;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace*)graph.defaultPlotSpace;
NSTimeInterval intervalSpan = [[graphDates lastObject] timeIntervalSinceReferenceDate] - [[graphDates firstObject] timeIntervalSinceReferenceDate];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0) length:CPTDecimalFromDouble(intervalSpan)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(graphMin) length:CPTDecimalFromInt(graphMax)];
Where graphDates hold the smallest and the biggest date in a sorted order, which is a few days back and just now respectively in my case.
My graph and my plot area frame have a lot of padding at all sides, so it doesn't seem to be the common padding issue. What else causes labels not to display?
The problem was specific to El Capitan and Core Plot and it was addressed by the framework.

how dynamically add many label with different name into scrollview

Below is my code...to generate many label for Quiz App to show answer
for (NSInteger i = 0, y = 50; i < 3 ; i++, y += 30) {
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 100, 25)];
_optoin1 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]; _op1.text= _optoin1;
nameLabel.text =_optoin1;
[_myscrollView addSubview:nameLabel];
sqlite3_finalize(statement);
key++;
}
key is used get next columnvalue from db.It generate four label..
for (NSInteger i = 0, y = 50; i < 4 ; i++, y += 30)
{
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, y, 100, 25)];
_optoin1 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, key)];
nameLabel.tag = labl_id;
nameLabel.text =_optoin1;
[_myscrollView addSubview:nameLabel];
//sqlite3_finalize(statement);
key++;
labl_id++;
}

RemoveFromSuperview is not cleaning-up memory

I'm programmatically creating labels in a function and putting them into an NSMutableArray, then I delete them from another function.
The problem is that the labels actually disappear from screen but they're still using memory and when some time passes the program starts to work very slow.
Here is my code:
This is the function that creates the labels.
- (void)CrearEstrellas{
for(int i=0; i< 10; i++)
{
float x = arc4random() %300;
float y = arc4random() %100;
UILabel *estrella = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 4, 4)];
estrella.tag = i;
estrella.center = CGPointMake(x,y-100);
estrella.text = #".";
estrella.textColor = [UIColor whiteColor];
[self.view.superview addSubview: estrella];
[arrayEstrellas insertObject:(estrella) atIndex: i];
}
}
And this is the function that delete them from the superview:
- (void)Lineatiempo{
for(int i=0; i<[arrayEstrellas count]; i++)
{
UILabel *estrella = [arrayEstrellas objectAtIndex:(i)];
float x = estrella.center.x;
float y = estrella.center.y;
estrella.center = CGPointMake(x,y+10);
if(estrella.center.y>200){
[estrella removeFromSuperview];
estrella = nil;
}
}
}
I would like to know what am i doing wrong! Thanks.
You add the view to an array. NSArray (and NSMutableArray) retain the objects you add to them. The aren't deallocated until you remove them from the array.
So in addition to calling removeFromSuperview you also have to remove the view from the array.

Two y axis in core plot graph with different axis scales

I am programming a app where I have graph with two y axis and one x axis.left y axis has range from 0 to 20 so there are 20 majorTick axis.Right y axis has range from 0 to 10,so I want left y axis to be labelled for every alternate majorTickAxis.
here is my code snippet
//code
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
float xmax=10.0;
float xmin=0.0;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xmin) length:CPTDecimalFromFloat(xmax-xmin)];
float ymax=20.0;
float ymin=0.0;
float ymax2=10.0;
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(ymin) length:CPTDecimalFromFloat(ymax-ymin)];
// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.75];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
CPTMutableLineStyle *redLineStyle = [CPTMutableLineStyle lineStyle];
redLineStyle.lineWidth = 2.0;
redLineStyle.lineColor = [[CPTColor redColor] colorWithAlphaComponent:0.5];
CPTMutableLineStyle *greenLineStyle = [CPTMutableLineStyle lineStyle];
greenLineStyle.lineWidth = 2.0;
greenLineStyle.lineColor = [[CPTColor greenColor] colorWithAlphaComponent:0.5];
// Axes
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.orthogonalCoordinateDecimal = CPTDecimalFromString(#"0");
x.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:#"1"] decimalValue];
x.minorTicksPerInterval = 4;
x.labelOffset = 3.0f;
x.title = #"Time";
x.titleOffset = 20.0;
x.titleLocation = CPTDecimalFromFloat((xmax+xmin)/2);
x.majorGridLineStyle= majorGridLineStyle;
x.minorGridLineStyle=minorGridLineStyle;
CPTXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPTDecimalFromString(#"1.0");
y.majorTickLength=2.0f;
y.minorTicksPerInterval = 4;
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0);
y.labelExclusionRanges = [NSArray arrayWithObjects:
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0.0)
length:CPTDecimalFromInteger(0.0)],Nil];
y.majorGridLineStyle= majorGridLineStyle;
y.minorGridLineStyle=minorGridLineStyle;
CPTXYAxis *y2 = [[(CPTXYAxis *)[CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
y2.plotSpace =plotSpace;
y2.orthogonalCoordinateDecimal = CPTDecimalFromFloat(xmax);
y2.majorGridLineStyle=majorGridLineStyle;
y2.minorGridLineStyle=minorGridLineStyle;
y2.minorTicksPerInterval = 4;
y2.majorIntervalLength = CPTDecimalFromString(#"1.0");
y2.labelOffset = 10.0;
y2.coordinate =CPTCoordinateY;
y2.axisLineStyle = x.axisLineStyle;
y2.labelTextStyle = x.labelTextStyle;
y2.labelOffset = -30.0f;
y2.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger(ymax2)];
y2.title = #"Temperature";
y2.titleLocation = CPTDecimalFromInteger(5.0);
y2.titleTextStyle =x.titleTextStyle;
y2.titleOffset =-45.0f;
y2.labelExclusionRanges = [NSArray arrayWithObjects:
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0.0)
length:CPTDecimalFromInteger(0.0)],Nil];
self.graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];
// Create a plot that uses the data source method for red graph
CPTScatterPlot *redPlot = [[[CPTScatterPlot alloc] init] autorelease];
redPlot.identifier = #"red Plot";;
CPTMutableLineStyle *lineStyle = [[redPlot.dataLineStyle mutableCopy] autorelease];
lineStyle.miterLimit = 1.0f;
redPlot.dataLineStyle = redLineStyle;
redPlot.dataSource = self;
redPlot.interpolation = CPTScatterPlotInterpolationStepped;
[self.graph addPlot:redPlot];
// Create a plot that uses the data source method for green graph
CPTScatterPlot *greenPlot = [[[CPTScatterPlot alloc] init] autorelease];
greenPlot.identifier = #"green Plot";;
CPTMutableLineStyle *greenlineStyle = [[greenPlot.dataLineStyle mutableCopy] autorelease];
greenlineStyle.miterLimit = 1.0f;
greenPlot.dataLineStyle = greenLineStyle;
greenPlot.dataSource = self;
[self.graph addPlot:greenPlot];
// Add some data
NSMutableArray *newData = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for ( i = 0; i < 45; i++ ) {
id x = [NSNumber numberWithDouble:i * 0.2];
id y = [NSNumber numberWithDouble:i * rand() / ((double)RAND_MAX*5.0) ];
[newData addObject:[NSDictionary dictionaryWithObjectsAndKeys:
x, #"x",y, #"y",nil]];
}
NSMutableArray *newData1 = [NSMutableArray arrayWithCapacity:100];
for ( i = 0; i < 45; i++ ) {
id x =[NSNumber numberWithDouble:i * rand() / ((double)RAND_MAX*5.0) ];
id y2 = [NSNumber numberWithDouble:i * 0.2];
[newData1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:
x, #"x",y2, #"y2",nil]];
}
self.plotData = newData;
self.plotData2=newData1;
If you want the two y-axes to have different scales, you need to add another plot space. Use the same xRange for the second plot space, but use a different yRange, e.g.,
CPTXYPlotSpace *plotSpace2 = [[[CPTXYPlotSpace alloc] init] autorelease];
plotSpace2.xRange = plotSpace.xRange;
plotSpace2.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(ymin)
length:CPTDecimalFromFloat(ymax2 - ymin)];
[graph addPlotSpace:plotSpace2];
y2.plotSpace = plotSpace2;
Use the majorIntervalLength to control the location of the ticks and grid lines:
y.majorIntervalLength = CPTDecimalFromFloat((ymax - ymin) / 10.0f);
y2.majorIntervalLength = CPTDecimalFromFloat((ymax2 - ymin) / 10.0f);

Resources