how dynamically add many label with different name into scrollview - xcode

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

Related

calculate height and width based on text , font , text color in xcode

what is the best way to calculate (formated text including text size , text color , text font) proper height and width of text field in a fixed UIView , including word wrap etc
in the following image text is not right align Check the Image
in the following image text is not properly showing check the image
i am calculating image height and width with the following code
NSString* text=[textField stringValue];
NSDictionary *attributes;
NSTextView* textView =[[NSTextView alloc] init];
[textView setString:text];
attributes = #{NSFontAttributeName : [NSFont fontWithName:fontName size:fontValue], NSForegroundColorAttributeName : [NSColor colorWithCalibratedRed:redValueTextColor green:GreenValueTextColor blue:blueValueTextColor alpha:1], NSBackgroundColorAttributeName : [NSColor colorWithCalibratedRed:redValueTextBackgroundColor green:GreenValueTextBackgroundColor blue:blueValueTextBackgroundColor alpha:1]};
textView.backgroundColor=[NSColor colorWithCalibratedRed:redValueTextBackgroundColor green:GreenValueTextBackgroundColor blue:blueValueTextBackgroundColor alpha:1];
NSInteger maxWidth = 600;
NSInteger maxHeight = 20000;
CGSize constraint = CGSizeMake(maxWidth, maxHeight);
NSRect newBounds = [text boundingRectWithSize:constraint options:NSLineBreakByCharWrapping|NSStringDrawingUsesFontLeading attributes:attributes];
textView.frame = NSMakeRect(textView.frame.origin.x, textView.frame.origin.y, newBounds.size.width, newBounds.size.height);
textView =[NSColor colorWithCalibratedRed:redValueTextColor green:GreenValueTextColor blue:blueValueTextColor alpha:1];
[textView setFont:[NSFont fontWithName:fontName size:fontValue]];
Core Text solution (note, maxWidth allows wrapping if you want it):
(CGSize)sizeForText:(NSAttributedString *)string maxWidth:(CGFloat)width
{
CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);
CFIndex offset = 0, length;
CGFloat y = 0, lineHeight;
do {
length = CTTypesetterSuggestLineBreak(typesetter, offset, width);
CTLineRef line = CTTypesetterCreateLine(typesetter, CFRangeMake(offset, length));
CGFloat ascent, descent, leading;
CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CFRelease(line);
offset += length;
ascent = roundf(ascent);
descent = roundf(descent);
leading = roundf(leading);
lineHeight = ascent + descent + leading;
lineHeight = lineHeight + ((leading > 0) ? 0 : roundf(0.2*lineHeight)); //add 20% space
y += lineHeight;
} while (offset < [string length]);
CFRelease(typesetter);
return CGSizeMake(width, y);
}

Calculate input from textfield in a loop

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

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

Programmatically get screen size in Mac OS X

I am able to return the screen size using:
- (void) getScreenResolution {
NSArray *screenArray = [NSScreen screens];
NSScreen *mainScreen = [NSScreen mainScreen];
unsigned screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
NSScreen *screen = [screenArray objectAtIndex: index];
NSRect screenRect = [screen visibleFrame];
NSString *mString = ((mainScreen == screen) ? #"Main" : #"not-main");
NSLog(#"Screen #%d (%#) Frame: %#", index, mString, NSStringFromRect(screenRect));
}
}
Output:
Screen #0 (Main) Frame: {{0, 4}, {1344, 814}}
Is there a way to format {1344, 814} to 1344x814?
Edit:
This works perfectly:
- (NSString*) screenResolution {
NSRect screenRect;
NSArray *screenArray = [NSScreen screens];
unsigned screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
NSScreen *screen = [screenArray objectAtIndex: index];
screenRect = [screen visibleFrame];
}
return [NSString stringWithFormat:#"%.1fx%.1f",screenRect.size.width, screenRect.size.height];
}
In Swift 4.0 you can get the screen size of the main screen:
if let screen = NSScreen.main {
let rect = screen.frame
let height = rect.size.height
let width = rect.size.width
}
If you look for the size of the screen with a particular existing window you can get it with:
var window: NSWindow = ... //The Window laying on the desired screen
var screen = window.screen!
var rect = screen.frame
var height = rect.size.height
var width = rect.size.width
Finding the screen size in Mac OS is very simple:
NSRect e = [[NSScreen mainScreen] frame];
H = (int)e.size.height;
W = (int)e.size.width;
NSLog(#"%fx%f",screenRect.size.width, screenRect.size.height);
edit/update
Swift 4
NSScreen.main?.frame // {x 0 y 0 w 1,920 h 1,200}
NSScreen.main?.frame.width // 1,920.0
NSScreen.main?.frame.height // 1,200.0
Swift 3.x
NSScreen.main()?.frame // {x 0 y 0 w 1,920 h 1,200}
NSScreen.main()?.frame.width // 1,920.0
NSScreen.main()?.frame.height // 1,200.0
Swift 2.x
NSScreen.mainScreen()?.frame // {x 0 y 0 w 1,920 h 1,200}
NSScreen.mainScreen()?.frame.width // 1,920.0
NSScreen.mainScreen()?.frame.height // 1,200.0
For those guy who are looking for a way to get screen resolution:
If you are programming a window based app, you can simply get the resolution from _window.screen.frame.size
Swift 3 solution:
NSScreen.main()!.frame

Resources