Group creation UI object in objective-c - ios

I have this code. I would like to make it more compact. Is it possible to add the groups similar controls?
UILabel *controlFreeName = [[UILabel alloc] init];
controlFreeName.frame = CGRectMake(40.0f, 70.0f, 120.0f, 50.0f);
controlFreeName.text = #"Free";
UILabel *controlNoFreeName = [[UILabel alloc] init];
controlNoFreeName.frame = CGRectMake(40.0f, 110.0f, 120.0f, 50.0f);
controlNoFreeName.text = #"No free";
UILabel *controlEquipmentName = [[UILabel alloc] init];
controlEquipmentName.frame = CGRectMake(40.0f, 150.0f, 120.0f, 50.0f);
controlEquipmentName.text = #"Equipment";
UILabel *controlTypeName = [[UILabel alloc] init];
controlTypeName.frame = CGRectMake(40.0f, 190.0f, 180.0f, 50.0f);
controlTypeName.text = #"Type";

Try something like this
NSArray * myArray = [[NSArray alloc]initWithObjects:#"Test1",#"Test2",#"Test2", nil];
for (int i = 0; i < 3; i++)
{
UILabel * myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10*5*i, 10*5*i, 100, 100)];
myLabel.text = [myArray objectAtIndex:i];
int r = arc4random() % 255;
int g = arc4random() % 255;
int b = arc4random() % 255;
myLabel.backgroundColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1];
[self.view addSubview: myLabel];
}

Related

Create Dynamic textField

I am developing IOS App. I Create TextField and Button Dynamically and Set tag value.but problem is that when click button to get textfield first index value that show null. only last index value of textfield i am get not for other What is the problem. Thanks in Advance.
Code..
- (void)addfields{
_field = [[UITextField alloc]initWithFrame:CGRectMake(5.0f, 5.0f, 195.0f, 30.0f)];
_field.layer.borderColor=[[UIColor colorWithRed:211.0f/255.0f
green:211.0f/255.0f
blue:211.0f/255.0f
alpha:1.0] CGColor];
[_field.layer setBorderWidth: 1.0];
//_field.tag = count;
[_filterPossibleValueView addSubview:_field];
_addField = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, 5.0f, 30.0f, 30.0f)];
_addField.backgroundColor = [UIColor blackColor];
//_addField.tag = count;
[_addField addTarget:self action:#selector(customFieldAdd:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:_addField];
}
- (IBAction)customFieldAdd:(id)sender{
[_addfieldArray addObject:_field];
[_scroller setScrollEnabled:YES];
_scroller.contentSize=CGSizeMake(240.0f, _field.frame.size.height+x+50);
[_copyfield removeFromSuperview];
[copyAddButton removeFromSuperview];
x = 10;
y = 10;
for( int i = 0; i < [_addfieldArray count]; i++ ) {
_copyfield = [[UITextField alloc]initWithFrame:CGRectMake(5.0, x + _field.frame.size.height, 195.0f, 30.0f)];
_copyfield.layer.borderColor=[[UIColor colorWithRed:211.0f/255.0f
green:211.0f/255.0f
blue:211.0f/255.0f
alpha:1.0] CGColor];
_copyfield.tag = i;
[_copyfield.layer setBorderWidth: 1.0];
[_filterPossibleValueView addSubview:_copyfield];
x = x+_field.frame.size.height+10;
copyAddButton = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, y + _addField.frame.size.height, 30.0f, 30.0f)];
copyAddButton.backgroundColor = [UIColor blueColor];
copyAddButton.tag = i;
[copyAddButton addTarget:self action:#selector(customFieldDelete:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:copyAddButton];
y = y+_addField.frame.size.height+10;
count++;
}
}
- (IBAction)customFieldDelete:(id)sender{
UIButton *button = (UIButton*)sender;
NSInteger index = button.tag;
[_addfieldArray removeObjectAtIndex:index];
// UITextField *text = (UITextField *)[_copyfield viewWithTag:index];
// NSLog(#"%ld",(long)text.tag);
UITextField *txtField = [_filterPossibleValueView viewWithTag:index];
NSLog(#"%#",txtField.text);
// [_copyfield removeFromSuperview];
// [copyAddButton removeFromSuperview];
}
I have created an sample app for dynamic fields. And getting the textfield's value on Button click. This example code will solve out your problem.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
NSMutableArray *formArr;
NSMutableArray *txtfldArr;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
formArr = [[NSMutableArray alloc] init];
txtfldArr = [[NSMutableArray alloc] init];
UITextField *txtfld = [[UITextField alloc] init];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:#"string" forKey:#"labelName"];
[dict1 setObject:#"name" forKey:#"labelFor"];
[dict1 setObject:#"1" forKey:#"tag"];
[dict1 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict1];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
[dict2 setObject:#"string" forKey:#"labelName"];
[dict2 setObject:#"email" forKey:#"labelFor"];
[dict2 setObject:#"2" forKey:#"tag"];
[dict2 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict2];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
[dict3 setObject:#"string" forKey:#"labelName"];
[dict3 setObject:#"phone" forKey:#"labelFor"];
[dict3 setObject:#"3" forKey:#"tag"];
[dict3 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict3];
NSMutableDictionary *dict4 = [[NSMutableDictionary alloc] init];
[dict4 setObject:#"string" forKey:#"labelName"];
[dict4 setObject:#"address" forKey:#"labelFor"];
[dict4 setObject:#"4" forKey:#"tag"];
[dict4 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict4];
int y = 70;
for (int i = 0; i < [formArr count]; i++) {
NSString *txtfldName = [NSString stringWithFormat:#"%#",[[formArr objectAtIndex:i] objectForKey:#"labelFor"]];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(30, y+4, 80, 25)];
lbl.text = txtfldName;
lbl.textColor = [UIColor darkGrayColor];
[self.view addSubview:lbl];
UITextField *lbl_txtfld = [[UITextField alloc] initWithFrame:CGRectMake(120, y, 150, 30)];
lbl_txtfld.text = #"";
lbl_txtfld.delegate = self;
lbl_txtfld.textColor = [UIColor whiteColor];
lbl_txtfld.backgroundColor = [UIColor blackColor];
[self.view addSubview:lbl_txtfld];
[[formArr objectAtIndex:i] setObject:lbl_txtfld forKey:#"txtFld"];
y += 40;
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonClicked:(id)sender {
for (int i = 0; i < [formArr count]; i++) {
NSString *labelName = [NSString stringWithFormat:#"%#",[[formArr
objectAtIndex:i] objectForKey:#"labelFor"]];
UITextField *txtfld = [[formArr objectAtIndex:i]
objectForKey:#"txtFld"];
NSLog(#"txtfld value for %# = %#",labelName,txtfld.text);
}
}

UIscrollView To scroll images horizontally and show images from the image clicked

I have four images on a viewcontroller.On the click of those images a newViewController i.e. LargeImageViewController opens. On the LargeImageViewController there is ScrollView which does horizontal scrolling. On click of every button the images on LargeImageViewController starts from image1 ,then shows image2,then image 3,then image 4.
I want that if image 2 is clicked then the images on LargeImageViewController should start image2,then image 3,then image 4.....but when it goes to previous image then it should show image 4,image3,image 2 and image1 also.
How this can be achieved??
Code that I am using are as follows:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// int pageCount=4;
NSArray *imgArray = [self.tripDetails valueForKey:#"Flightimageurl"];
width = [UIScreen mainScreen].bounds.size.width;
height = [UIScreen mainScreen].bounds.size.height;
_scroller = [[UIScrollView alloc]initWithFrame:
CGRectMake(0,64,width,height)];
_scroller.contentSize=CGSizeMake([imgArray count]*_scroller.bounds.size.width,_scroller.bounds.size.height);
CGRect ViewSize=_scroller.bounds;
for(int i=0;i<[imgArray count];i++)
{
UIImageView *imgView1=[[UIImageView alloc]initWithFrame:ViewSize];
NSString *ImageURL = [imgArray objectAtIndex:i];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
imgView1.image=[UIImage imageWithData:imageData];
[_scroller addSubview:imgView1];
[self.view addSubview:_scroller];
ViewSize =CGRectOffset(ViewSize,_scroller.bounds.size.width,0);
}
}
Kindly help with suggesting the changes.
-(void)singleTapping:(UIGestureRecognizer *)recognizer {
int imageTag = (int) recognizer.view.tag;
NSDictionary *dictCurrentWish = [arrLatestScrollData objectAtIndex:pageNumberSaved];
scrollimagePostView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, kSCREEN_WIDTH, kSCREEN_HEIGHT)];
scrollimagePostView.pagingEnabled=YES;
scrollimagePostView.delegate=self;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleGesture:)];
[scrollimagePostView addGestureRecognizer:gr];
NSMutableArray *arrTotalImages = [[NSMutableArray alloc]initWithCapacity:0];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic1"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic2"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic3"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic4"]];
int x=0;
CGRect innerScrollFrame = scrollimagePostView.bounds;
for (int i=0; i<arrTotalImages.count; i++) {
imgViewPost=[[UIImageView alloc]initWithFrame:CGRectMake(x, 60, kSCREEN_WIDTH,kSCREEN_HEIGHT-90)];
NSString *strImage =[NSString stringWithFormat:#"%#", [arrTotalImages objectAtIndex:i]];
NSString *strURL=[strImage stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL* urlAddress1 = [[NSURL alloc] initWithString:strURL];
[imgViewPost sd_setImageWithURL:urlAddress1 placeholderImage:wishPlaceHolderImage];
imgViewPost.contentMode = UIViewContentModeScaleAspectFit;
imgViewPost.tag = VIEW_FOR_ZOOM_TAG;
UIScrollView *pageScrollView = [[UIScrollView alloc]
initWithFrame:innerScrollFrame];
pageScrollView.minimumZoomScale = 1.0f;
pageScrollView.maximumZoomScale = 6.0f;
pageScrollView.zoomScale = 1.0f;
pageScrollView.contentSize = imgViewPost.bounds.size;
pageScrollView.delegate = self;
pageScrollView.showsHorizontalScrollIndicator = NO;
pageScrollView.showsVerticalScrollIndicator = NO;
[pageScrollView addSubview:imgViewPost];
[scrollimagePostView addSubview:imgViewPost];
x=x+kSCREEN_WIDTH;
if (i < 2) {
innerScrollFrame.origin.x += innerScrollFrame.size.width;
}
}
scrollimagePostView.contentSize = CGSizeMake(x, scrollimagePostView.frame.size.height );
scrollimagePostView.backgroundColor = [UIColor blackColor];
[self.view addSubview:scrollimagePostView];
[scrollimagePostView setContentOffset:CGPointMake(scrollimagePostView.frame.size.width*(imageTag-1), 0.0f) animated:NO];
btnCloseFullIMageView = [[UIButton alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH-80, 25, 70, 25)];
[btnCloseFullIMageView setTitle:#"Close" forState:UIControlStateNormal];
[btnCloseFullIMageView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btnCloseFullIMageView.backgroundColor = [UIColor blackColor];
btnCloseFullIMageView.layer.borderColor = [UIColor whiteColor].CGColor;
btnCloseFullIMageView.layer.borderWidth = 0.5;
btnCloseFullIMageView.layer.cornerRadius = 3.0;
btnCloseFullIMageView.clipsToBounds = TRUE;
[btnCloseFullIMageView addTarget:self action:#selector(closeFullImageView:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnCloseFullIMageView];
}

Images on horizontal scroll view according to clicked image

I have four images on a Viewcontroller A .On the click of those images Viewcontroller B having UIScrollView presents that has image view and it shows all those four imgaes....Image1 ,image 2,image 3,image 4.
I want that when image 2 is clicked then image 2 appeas as the first image on Viewcontroller B ,then image 3,then image 4...Also,when user moves left then it shows previous images including image1 too.
I have searched a lot but couldn't find solution to this problem Kindly.help
The code I have used are as follows:
- (void)viewDidLoad {
[super viewDidLoad];
width = [UIScreen mainScreen].bounds.size.width;
height = [UIScreen mainScreen].bounds.size.height;
_scroller = [[UIScrollView alloc]initWithFrame:
CGRectMake(0,64,width,height)];
_scroller.contentSize=CGSizeMake(pageCount*_scroller.bounds.size.width,_scroller.bounds.size.height);
_scroller.pagingEnabled=YES;
_scroller.showsHorizontalScrollIndicator=YES;
CGRect ViewSize=_scroller.bounds;
NSArray *imgArray = [self.tripDetails valueForKey:#"Flightimageurl"];
for(int i=0;i<[imgArray count];i++)
{
UIImageView *imgView1=[[UIImageView alloc]initWithFrame:ViewSize];
NSString *ImageURL = [imgArray objectAtIndex:i];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
imgView1.image=[UIImage imageWithData:imageData];
[_scroller addSubview:imgView1];
[self.view addSubview:_scroller];
ViewSize =CGRectOffset(ViewSize,_scroller.bounds.size.width,0);
}
}
Use This Code It will be helpful to you
-(void)singleTapping:(UIGestureRecognizer *)recognizer {
int imageTag = (int) recognizer.view.tag;
NSDictionary *dictCurrentWish = [arrLatestScrollData objectAtIndex:pageNumberSaved];
scrollimagePostView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, kSCREEN_WIDTH, kSCREEN_HEIGHT)];
scrollimagePostView.pagingEnabled=YES;
scrollimagePostView.delegate=self;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleGesture:)];
[scrollimagePostView addGestureRecognizer:gr];
NSMutableArray *arrTotalImages = [[NSMutableArray alloc]initWithCapacity:0];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic1"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic2"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic3"]];
[arrTotalImages addObject:[dictCurrentWish objectForKey:#"pic4"]];
int x=0;
CGRect innerScrollFrame = scrollimagePostView.bounds;
for (int i=0; i<arrTotalImages.count; i++) {
imgViewPost=[[UIImageView alloc]initWithFrame:CGRectMake(x, 60, kSCREEN_WIDTH,kSCREEN_HEIGHT-90)];
NSString *strImage =[NSString stringWithFormat:#"%#", [arrTotalImages objectAtIndex:i]];
NSString *strURL=[strImage stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL* urlAddress1 = [[NSURL alloc] initWithString:strURL];
[imgViewPost sd_setImageWithURL:urlAddress1 placeholderImage:wishPlaceHolderImage];
imgViewPost.contentMode = UIViewContentModeScaleAspectFit;
imgViewPost.tag = VIEW_FOR_ZOOM_TAG;
UIScrollView *pageScrollView = [[UIScrollView alloc]
initWithFrame:innerScrollFrame];
pageScrollView.minimumZoomScale = 1.0f;
pageScrollView.maximumZoomScale = 6.0f;
pageScrollView.zoomScale = 1.0f;
pageScrollView.contentSize = imgViewPost.bounds.size;
pageScrollView.delegate = self;
pageScrollView.showsHorizontalScrollIndicator = NO;
pageScrollView.showsVerticalScrollIndicator = NO;
[pageScrollView addSubview:imgViewPost];
[scrollimagePostView addSubview:imgViewPost];
x=x+kSCREEN_WIDTH;
if (i < 2) {
innerScrollFrame.origin.x += innerScrollFrame.size.width;
}
}
scrollimagePostView.contentSize = CGSizeMake(x, scrollimagePostView.frame.size.height );
scrollimagePostView.backgroundColor = [UIColor blackColor];
[self.view addSubview:scrollimagePostView];
[scrollimagePostView setContentOffset:CGPointMake(scrollimagePostView.frame.size.width*(imageTag-1), 0.0f) animated:NO];
btnCloseFullIMageView = [[UIButton alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH-80, 25, 70, 25)];
[btnCloseFullIMageView setTitle:#"Close" forState:UIControlStateNormal];
[btnCloseFullIMageView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btnCloseFullIMageView.backgroundColor = [UIColor blackColor];
btnCloseFullIMageView.layer.borderColor = [UIColor whiteColor].CGColor;
btnCloseFullIMageView.layer.borderWidth = 0.5;
btnCloseFullIMageView.layer.cornerRadius = 3.0;
btnCloseFullIMageView.clipsToBounds = TRUE;
[btnCloseFullIMageView addTarget:self action:#selector(closeFullImageView:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnCloseFullIMageView];
}

UILabel updating text, but won't remove old text

EDIT: I figured out that i needed to remove subviews, once the view did disappear
[[self.scrollView subviews]makeObjectsPerformSelector:#selector(removeFromSuperview)];
My problem is that I have an UILabel which updates the text correctly, but won't remove the old text. I think maybe it's because there are 2 UILabels on top of each other, here is a picture of it:
And here is my code. I can't see where the duplicate is:
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
float progressScore = ((float)myScore/(float)levelScore);
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [UIColor clearColor];
NSArray *colorArray = [NSArray arrayWithObjects:edmeral, turqouise, orange, red, nil];
// Labeled progress views
self.labeledProgressView = [[DALabeledCircularProgressView alloc]
initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
self.labeledProgressView.roundedCorners = NO;
self.labeledProgressView.trackTintColor = [UIColor colorWithWhite:1.0f alpha:0.8];
imageLevel = [[UIImageView alloc] initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
imageLevel.backgroundColor = [UIColor clearColor];
self.Scoreint = [[UILabel alloc] initWithFrame:CGRectMake(-25.0f, 130, 195, 21)];
self.Scoreint.backgroundColor = [UIColor clearColor];
self.Scoreint.textColor = [UIColor blackColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
if (myScore == 0) {
NSString *scoreString = [NSString stringWithFormat:#"0 / %5ld", (long)levelScore];
[self.Scoreint setText:scoreString];
}
else {
NSString *scoreString = [NSString stringWithFormat:#"%5li / %5li", (long)myScore, (long)levelScore];
[self.Scoreint setText:scoreString];
}
[subview addSubview:Scoreint];
I hope some of you guys can help me out with this! :)
the other way, you should do it, it's remove the label from superView everytime, before you initialize it.
You modify the code like this,
if(self.Scoreint) {
[self.Scoreint removeFromSuperview];
}
self.Scoreint = [[UILabel alloc] initWithFrame:CGRectMake(-25.0f, 130, 195, 21)];
self.Scoreint.backgroundColor = [UIColor clearColor];
self.Scoreint.textColor = [UIColor blackColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
that happens because you instantiate the UILabel each time, You have to instantiate the it only once, outside the for loop, and then just change the title.
This might work, i haven't tried it
self.Scoreint = [[UILabel alloc] initWithFrame:CGRectMake(-25.0f, 130, 195, 21)];
self.Scoreint.backgroundColor = [UIColor clearColor];
self.Scoreint.textColor = [UIColor blackColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
for (int i = 0; i < array1.count; i++) {
NSNumber *myNumber = [myscoretext objectAtIndex:i];
float myScore = myNumber.floatValue;
NSNumber *levelNumber = [neededscoretext objectAtIndex:i];
float levelScore = levelNumber.floatValue;
float progressScore = ((float)myScore/(float)levelScore);
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [UIColor clearColor];
NSArray *colorArray = [NSArray arrayWithObjects:edmeral, turqouise, orange, red, nil];
// Labeled progress views
self.labeledProgressView = [[DALabeledCircularProgressView alloc]
initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
self.labeledProgressView.roundedCorners = NO;
self.labeledProgressView.trackTintColor = [UIColor colorWithWhite:1.0f alpha:0.8];
imageLevel = [[UIImageView alloc] initWithFrame:CGRectMake(25.0f, 20.0f, 100.0f, 100.0f)];
imageLevel.backgroundColor = [UIColor clearColor];
[self.Scoreint setFont:[UIFont fontWithName:#"HelveticaNeue-Thin" size:15]];
self.Scoreint.textAlignment = NSTextAlignmentCenter;
self.Scoreint.text = #"";
if (myScore == 0) {
NSString *scoreString = [NSString stringWithFormat:#"0 / %5ld", (long)levelScore];
[self.Scoreint setText:scoreString];
}
else {
NSString *scoreString = [NSString stringWithFormat:#"%5li / %5li", (long)myScore, (long)levelScore];
[self.Scoreint setText:scoreString];
}
[subview addSubview:Scoreint];
In similar situation, the property of UIView’s visual appearance helped me. Try this:
self.Scoreint.clearsContextBeforeDrawing = true

Terminated due to Memory Error when load number of view into UIScrollView

I am using UIScrollView in my app that 25 view first time.
user scroll on bottom next 25 view add in scrollview.
I am still entirely not sure this is a memory problem.But i didn't found the code cause of the Memory Problem.
Even I have checked memory leak issue through the instrument tool there is no memory leak.
My code:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
float scrollViewHeight = _scrl_ipad.frame.size.height;
float scrollContentSizeHeight = _scrl_ipad.contentSize.height;
float scrollOffset = _scrl_ipad.contentOffset.y;
if (scrollOffset == 0)
{
}
else if (scrollOffset + scrollViewHeight == scrollContentSizeHeight)
{
if (scrl_bottom_reload_view)
{
scrl_bottom_reload_view=nil;
[scrl_bottom_reload_view release];
}
scrl_bottom_reload_view = [[UIView alloc]initWithFrame:CGRectMake(10, scrollContentSizeHeight-100, _scrl_ipad.frame.size.width-20, 60.0)];
scrl_bottom_reload_view.tag = -50;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake((_scrl_ipad.frame.size.width/2)-100, 10, 200, 40)];
lbl.font = [UIFont fontWithName:#"ArialMT" size:22];
lbl.textColor = [UIColor darkGrayColor];
lbl.backgroundColor = [UIColor clearColor];
lbl.text = #"Loading deals...";
[scrl_bottom_reload_view addSubview:lbl];
[lbl release];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.alpha = 1.0;
activityIndicator.color = [UIColor lightGrayColor];
activityIndicator.frame = CGRectMake((_scrl_ipad.frame.size.width/2)-150, 12, 37, 37);
activityIndicator.hidesWhenStopped = NO;
[scrl_bottom_reload_view addSubview:activityIndicator];
[activityIndicator startAnimating];
scrl_bottom_reload_view.hidden = FALSE;
scrl_bottom_reload_view.backgroundColor = [UIColor clearColor];
[self.scrl_ipad addSubview:scrl_bottom_reload_view];
[self performSelector:#selector(LoadScrl) withObject:nil afterDelay:0.3];
}
}
-(void)LoadScrl
{
//called api and fill arrayalldeals arry
[self func_scrl_ipad];
}
-(void)func_scrl_ipad
{
NSArray *viewsToRemove = [_scrl_ipad subviews];
for (UIView *view in viewsToRemove)
{
[view removeFromSuperview];
view = nil;
}
int temp;
if([arrayalldeals count] % 2 == 0)
{
temp = ([arrayalldeals count] / 2);
}
else
{
temp = ([arrayalldeals count] / 2) + 1;
}
_scrl_ipad.contentSize = CGSizeMake(768,(258*temp)+150);
_scrl_ipad.showsVerticalScrollIndicator=NO;
int x = 35;
int y = 35;
for (int i = 1 ; i <= [arrayalldeals count]; i++)
{
UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake(x, y, 328, 243)];
bgview.backgroundColor = [UIColor whiteColor];
//bgview.layer.borderWidth = 0;
//bgview.layer.cornerRadius = 0;
bgview.tag = i;
//bgview.layer.masksToBounds = YES;
//bgview.layer.borderColor =[[UIColor clearColor] CGColor];
//bgview.layer.shadowColor = [[UIColor whiteColor] CGColor];
//bgview.layer.shadowOffset = CGSizeMake(0.0, 0.0);
//bgview.layer.shadowOpacity = 0.0;
AsyncImageView *imageView = [[AsyncImageView alloc] initWithFrame:CGRectMake(0, 0, 328, 223)];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
imageView.layer.cornerRadius = 0;
imageView.imageURL =[NSURL URLWithString:[NSString stringWithFormat:#"%#uploads/%#-5.jpg",app.Main_url,[[arrayalldeals objectAtIndex:i-1] objectForKey:#"deal_id"]]];
//cell.autoresizesSubviews=YES;
[bgview addSubview:imageView];
[imageView release];
UIView *shadoeview = [[UIView alloc]initWithFrame:CGRectMake(0,115, 328, 112)];
CAGradientLayer *bgLayer = [BackgroundLayer greyGradient];
bgLayer.frame = shadoeview.bounds;
[shadoeview.layer insertSublayer:bgLayer atIndex:0];
shadoeview.alpha = 0.9;
[bgview addSubview:shadoeview];
[shadoeview release];
UIImageView *img_discount = [[UIImageView alloc]initWithFrame:CGRectMake(0,0, 57, 57)];
img_discount.image = [UIImage imageNamed:#"discount_tag.png"];
[bgview addSubview:img_discount];
[img_discount release];
UILabel *lbl_disc_text=[[UILabel alloc]init];
lbl_disc_text.frame=CGRectMake(-2,-10,100,20);
lbl_disc_text.backgroundColor=[UIColor clearColor];
lbl_disc_text.font = [UIFont fontWithName:#"ArialMT" size:14];
lbl_disc_text.textColor = [UIColor whiteColor];
int disc = 0;
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"])
{
int main_price = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"] intValue];
int disc_price = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"price"] intValue];
int multiply = disc_price *100 /main_price;
disc = 100 - multiply;
}
lbl_disc_text.text = [NSString stringWithFormat:#"- %d%%",disc];
[bgview addSubview:lbl_disc_text];
float degrees = -40; //the value in degrees
lbl_disc_text.transform = CGAffineTransformMakeRotation(degrees * M_PI/180);
[lbl_disc_text release];
UILabel *lbl_desc=[[UILabel alloc]init];
lbl_desc.frame=CGRectMake(8,162, 240, 50);
lbl_desc.backgroundColor=[UIColor clearColor];
lbl_desc.font = [UIFont fontWithName:#"Arial Rounded MT Bold" size:16];
lbl_desc.textColor = [UIColor whiteColor];
lbl_desc.numberOfLines = 2 ;
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"name"])
{
lbl_desc.text=[NSString stringWithFormat:#"%#",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"name"]];
}
else
{
lbl_desc.text=#"";
}
[bgview addSubview:lbl_desc];
[lbl_desc release];
UILabel *lbl_unprice=[[UILabel alloc]init];
lbl_unprice.frame=CGRectMake(255,165,60,20);
lbl_unprice.backgroundColor=[UIColor clearColor];
lbl_unprice.textAlignment = NSTextAlignmentRight;
lbl_unprice.textColor = [UIColor whiteColor];
lbl_unprice.font = [UIFont fontWithName:#"ArialMT" size:14];
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"])
{
int unprice = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"] intValue];
lbl_unprice.text = [NSString stringWithFormat:#"$%d",unprice];
}
else
{
lbl_unprice.text=[NSString stringWithFormat:#"$0"];
}
[bgview addSubview:lbl_unprice];
[lbl_unprice release];
NSString *str_price_line;
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"])
{
int unprice = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"value"] intValue];
str_price_line = [NSString stringWithFormat:#"$%d",unprice];
}
else
{
str_price_line=[NSString stringWithFormat:#"$0"];
}
UIFont *font = [UIFont fontWithName:#"ArialMT" size:14];
CGSize size = [(str_price_line ? str_price_line : #"") sizeWithFont:font constrainedToSize:CGSizeMake(281, 9999) lineBreakMode:NSLineBreakByWordWrapping];
int temp = 60 - size.width;
UILabel *lbl_line=[[UILabel alloc]init];
lbl_line.frame=CGRectMake(253+temp,174,size.width+4,2);
lbl_line.backgroundColor=[UIColor colorWithRed:252.0/255.0 green:36.0/255.0 blue:148.0/255.0 alpha:1.0];
float degre = -20; //the value in degrees
lbl_line.transform = CGAffineTransformMakeRotation(degre * M_PI/250);
[bgview addSubview:lbl_line];
[lbl_line release];
UILabel *lbl_price=[[UILabel alloc]init];
lbl_price.frame=CGRectMake(215,180, 100, 35);
lbl_price.textAlignment = NSTextAlignmentRight;
lbl_price.backgroundColor=[UIColor clearColor];
lbl_price.font = [UIFont fontWithName:#"ArialMT" size:24];
lbl_price.textColor = [UIColor colorWithRed:93.0/255.0 green:202.0/255.0 blue:242.0/255.0 alpha:1.0];
if([NSNull null] != [[arrayalldeals objectAtIndex:i-1] objectForKey:#"price"])
{
int price = [[[arrayalldeals objectAtIndex:i-1] objectForKey:#"price"] intValue];
lbl_price.text = [NSString stringWithFormat:#"$%d",price];
}
else
{
lbl_price.text=[NSString stringWithFormat:#"$0"];
}
[bgview addSubview:lbl_price];
[lbl_price release];
UILabel *lbl_bottom_view=[[UILabel alloc]init];
lbl_bottom_view.frame=CGRectMake(0,223, 328,20);
lbl_bottom_view.backgroundColor=[UIColor darkGrayColor];
[bgview addSubview:lbl_bottom_view];
[lbl_bottom_view release];
UILabel *lbl_vertical1=[[UILabel alloc]init];
lbl_vertical1.frame=CGRectMake(100,223,2,20);
lbl_vertical1.backgroundColor=[UIColor grayColor];
[bgview addSubview:lbl_vertical1];
[lbl_vertical1 release];
UILabel *lbl_vertical2=[[UILabel alloc]init];
lbl_vertical2.frame=CGRectMake(222,223,2,20);
lbl_vertical2.backgroundColor=[UIColor grayColor];
[bgview addSubview:lbl_vertical2];
[lbl_vertical2 release];
UILabel *lbl_address=[[UILabel alloc]init];
lbl_address.frame=CGRectMake(4,226, 94, 14);
lbl_address.textAlignment = NSTextAlignmentCenter;
lbl_address.backgroundColor=[UIColor clearColor];
lbl_address.font = [UIFont fontWithName:#"ArialMT" size:12];
lbl_address.textColor = [UIColor whiteColor];
if ((NSNull *)app.city_dict == NULL)
{
lbl_address.text= #"Vancouver";
}
else
{
lbl_address.text=[NSString stringWithFormat:#"%#",[app.city_dict objectForKey:#"title"]];
}
[bgview addSubview:lbl_address];
[lbl_address release];
//LeftTime
NSString *strDatehere = [NSString stringWithFormat:#"%#",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"d_expires"]];
NSDateFormatter *heredateFormatter = [[NSDateFormatter alloc] init];
[heredateFormatter setDateFormat:#"yyyy-MM-dd"]; // set date formate with your dates
NSDate *datehere = [heredateFormatter dateFromString: strDatehere];
NSTimeInterval timeDifference = [datehere timeIntervalSinceDate:[NSDate date]];
[heredateFormatter release];
double hours = timeDifference / 3600;
NSInteger remainder = ((NSInteger)timeDifference)% 3600;
double minutes = remainder / 60;
double seconds = remainder % 60;
NSString *strleft_time = [NSString stringWithFormat:#"%.0fh, %.0fm, %.0fs",hours,minutes,seconds];
UILabel *lbl_time=[[UILabel alloc]init];
lbl_time.frame=CGRectMake(105,226, 110, 14);
lbl_time.textAlignment = NSTextAlignmentCenter;
lbl_time.backgroundColor=[UIColor clearColor];
lbl_time.font = [UIFont fontWithName:#"ArialMT" size:12];
lbl_time.textColor = [UIColor whiteColor];
lbl_time.text=strleft_time;
[bgview addSubview:lbl_time];
[lbl_time release];
UILabel *lbl_bought=[[UILabel alloc]init];
lbl_bought.frame=CGRectMake(222,226, 98, 14);
lbl_bought.textAlignment = NSTextAlignmentCenter;
lbl_bought.backgroundColor=[UIColor clearColor];
lbl_bought.font = [UIFont fontWithName:#"ArialMT" size:12];
lbl_bought.textColor = [UIColor whiteColor];
lbl_bought.text= [NSString stringWithFormat:#"%# Bought",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"buys"]];
[bgview addSubview:lbl_bought];
[lbl_bought release];
UIButton *btn_scrl=[UIButton buttonWithType:UIButtonTypeCustom];
[btn_scrl setFrame:CGRectMake(0,0, 328, 243)];
btn_scrl.tag=i-1;
[btn_scrl addTarget:self action:#selector(btn_scrl_tag:) forControlEvents:UIControlEventTouchUpInside];
[bgview addSubview:btn_scrl];
UIButton *btn_fav=[UIButton buttonWithType:UIButtonTypeCustom];
[btn_fav setFrame:CGRectMake(285,5, 35, 35)];
if([[[arrayalldeals objectAtIndex:i-1] objectForKey:#"user_faves"] isEqualToString:#"1"])
{
[btn_fav setBackgroundImage:[UIImage imageNamed:#"all_deals_fave_pink_icon.png"] forState:UIControlStateNormal];
}
else
{
[btn_fav setBackgroundImage:[UIImage imageNamed:#"all_deals_fave_icon.png"] forState:UIControlStateNormal];
}
[btn_fav.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
if([[[arrayalldeals objectAtIndex:i-1] objectForKey:#"faves"] isEqualToString:#"0"])
{
[btn_fav setTitle:#"" forState:UIControlStateNormal];
}
else
{
[btn_fav setTitle:[NSString stringWithFormat:#"%#",[[arrayalldeals objectAtIndex:i-1] objectForKey:#"faves"]] forState:UIControlStateNormal];
}
btn_fav.tag=i-1;
[btn_fav addTarget:self action:#selector(btn_favorite:) forControlEvents:UIControlEventTouchUpInside];
[bgview addSubview:btn_fav];
[_scrl_ipad addSubview:bgview];
[bgview release];
if(i % 2 == 0)
{
y = y + 258;
x = 35;
}
else
{
x = 399;
}
}
}
}
////
now api called more then 10 times i got Terminated due to Memory Pressure Error and App crase
Didn't understand, what are you trying to do? But found many bugs in your code. List out some of them.
1) In this line, you already set as nil and try to release nil object. This won't release any object, this is main reason for memory leak.
if (scrl_bottom_reload_view)
{
scrl_bottom_reload_view=nil;
[scrl_bottom_reload_view release];
}
2) Try to assign nil to local variable which does nothing.
for (UIView *view in viewsToRemove)
{
[view removeFromSuperview];
view = nil;
}
3) Where did you release this object.
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc].....
Suggestion : Above code is more complex, try with Tableview. Use xib to like this job. Otherwise more complex to design as well consume more time to develop.

Resources