I am creating an iOS app that needs to run on all device. When creating a slideshow I did not want to have an image for each device. I creating a method to generate the images. It takes a background image, main sink image, and 2 UILabels and scales accordingly. For portrait orientation on all the devices it works perfectly. On the iPad I also need landscape. When I rotate it something goes wrong because it just stretches the images. I am not sure what is happening to my view bounds.
Sorry my code is so long.
-(void)viewDidLoad{
_screenSize = self.view.bounds.size;
_slideShowImageArray = [[NSMutableArray alloc] init];
_slideShow = [[NSMutableArray alloc] init];
for (int i = 1; i<=8; i++) {
[_slideShow addObject:[self slideNumber:[NSNumber numberWithInt:i]]];
}
[self generateImages];
_SlideImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, _screenSize.width, _screenSize.height)];
[[self view]addSubview:_SlideImageView];
[self setSlideNumber:[NSNumber numberWithInt:1]];
[self begin];
}
-(void)begin{
if ([_SlideNumber intValue] <=8) {
UIImage * toImage = [_slideShowImageArray objectAtIndex:[_SlideNumber intValue]-1];
[UIView transitionWithView:self.view
duration:1.0f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.SlideImageView.image = toImage;
} completion:^(BOOL finished) {
sleep(2);
[self begin];
}];
int SlideNumber = [_SlideNumber intValue];
int NewSlideNumber = SlideNumber+=1;
[self setSlideNumber:[NSNumber numberWithInt:NewSlideNumber]];
}
}
-(SlideShowObj*) slideNumber:(NSNumber*)number{
SlideShowObj * slideShowOBJ = [[SlideShowObj alloc] init];
UIImageView * counterTempImageView = [[UIImageView alloc]init];
NSString * imageName = [NSString stringWithFormat:#"bg%d.png",[number intValue]];
counterTempImageView.image = [UIImage imageNamed:imageName];
[slideShowOBJ setCounterTopIMG:counterTempImageView];
UIImageView * sinkTempImageView = [[UIImageView alloc]init];
imageName = [NSString stringWithFormat:#"sink%d.png",[number intValue]];
sinkTempImageView.image = [UIImage imageNamed:imageName];
[slideShowOBJ setSinkIMG:sinkTempImageView];
NSString * textAboveSink = #"";
NSString * textBelowSink = #"";
UIColor * textAboveSinkColor = [UIColor blackColor];
UIColor * textBelowSinkColor = [UIColor blackColor];
if ([number intValue]==1) {
textAboveSink = [NSString stringWithFormat:#"8 CAPTIVATING \nCOLORS"];
textBelowSink = [NSString stringWithFormat:#"Anthracite"];
textAboveSinkColor = [UIColor whiteColor];
textBelowSinkColor = [UIColor whiteColor];
}else if ([number intValue]==2) {
textAboveSink = [NSString stringWithFormat:#"TO ENHANCE \nANY DECOR"];
textBelowSink = [NSString stringWithFormat:#"Cinder"];
textAboveSinkColor = [UIColor whiteColor];
textBelowSinkColor = [UIColor whiteColor];
}else if ([number intValue]==3) {
textAboveSink = [NSString stringWithFormat:#"REAL TOUGH,\nFOR REAL LIFE"];
textBelowSink = [NSString stringWithFormat:#"Metallic Grey"];
textAboveSinkColor = [UIColor whiteColor];
textBelowSinkColor = [UIColor whiteColor];
}else if ([number intValue]==4) {
textAboveSink = [NSString stringWithFormat:#"HYGENIC+PLUS \nKEEPS IT CLEAN"];
textBelowSink = [NSString stringWithFormat:#"Café Brown"];
textAboveSinkColor = [UIColor blackColor];
textBelowSinkColor = [UIColor blackColor];
}else if ([number intValue]==5) {
textAboveSink = [NSString stringWithFormat:#"HEAT PROOF \nACID RESISTANT"];
textBelowSink = [NSString stringWithFormat:#"Truffle"];
textAboveSinkColor = [UIColor blackColor];
textBelowSinkColor = [UIColor blackColor];
}else if ([number intValue]==6) {
textAboveSink = [NSString stringWithFormat:#"SCRATCH RESISTANT \nSTAIN RESISTANT"];
textBelowSink = [NSString stringWithFormat:#"Biscotti"];
textAboveSinkColor = [UIColor whiteColor];
textBelowSinkColor = [UIColor whiteColor];
}else if ([number intValue]==7) {
textAboveSink = [NSString stringWithFormat:#"NON-FADING \nKEEPS IT CLEAN"];
textBelowSink = [NSString stringWithFormat:#"Biscuit"];
textAboveSinkColor = [UIColor whiteColor];
textBelowSinkColor = [UIColor whiteColor];
}else if ([number intValue]==8) {
textAboveSink = [NSString stringWithFormat:#"FOR THE LIFE \nOF THE SINK"];
textBelowSink = [NSString stringWithFormat:#"White"];
textAboveSinkColor = [UIColor whiteColor];
textBelowSinkColor = [UIColor whiteColor];
}
[slideShowOBJ setTopTextColor:textAboveSinkColor];
[slideShowOBJ setBottomTextColor:textBelowSinkColor];
[slideShowOBJ setTopText:textAboveSink];
[slideShowOBJ setBottomText:textBelowSink];
return slideShowOBJ;
}
-(void)generateImages{
for (int i = 1; i<=8; i++) {
UIImage * bgImage = [[(SlideShowObj*)[_slideShow objectAtIndex:i-1]counterTopIMG]image];
//find out the width and height ratio of your image.
double ratio = bgImage.size.width / bgImage.size.height;
//determine the calculate width according the height. here height is set as mainScreen.
double calculatedWidth = ratio * _screenSize.height;
UIImageView * bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, calculatedWidth, _screenSize.height)];
[[self view] addSubview:bgImageView];
bgImageView.image = [[(SlideShowObj*)[_slideShow objectAtIndex:i-1]counterTopIMG]image];
UIImage * image = [[(SlideShowObj*)[_slideShow objectAtIndex:i-1]sinkIMG]image];
//find out the width and height ratio of your image.
double ratio1 = image.size.width / image.size.height;
//determine the calculate width according the height. here height is set as mainScreen.
double calculatedWidth1 = ratio1 * (_screenSize.height)*.5;
double calculatedheight1 = ratio1 * _screenSize.width*.5;
UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(_screenSize.width/2-calculatedWidth1/2, ((_screenSize.height)/2-calculatedheight1/2)*1.3, calculatedWidth1, calculatedheight1)];
[[self view] addSubview:imageView];
imageView.image = [[(SlideShowObj*)[_slideShow objectAtIndex:i-1]sinkIMG]image];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
UIFont *helvFont28 = [UIFont fontWithName:#"Helvetica" size:28.0];
UIFont *helvFont24 = [UIFont fontWithName:#"Helvetica" size:24.0];
UILabel * topText = [[UILabel alloc] initWithFrame:CGRectMake(0, (_screenSize.height)/2-(_screenSize.height)*.4, _screenSize.width, 100)];
[topText setNumberOfLines:2];
[topText setFont:helvFont28];
[topText setTextAlignment:NSTextAlignmentCenter];
[topText setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.2]];
[topText setTextColor:[(SlideShowObj*)[_slideShow objectAtIndex:i-1]topTextColor]];
[[self view]addSubview:topText];
[topText setText:[(SlideShowObj*)[_slideShow objectAtIndex:i-1]topText]];
UILabel * bottomText = [[UILabel alloc] initWithFrame:CGRectMake(0, (_screenSize.height)/2+(_screenSize.height)*.3, _screenSize.width, 40)];
[bottomText setFont:helvFont24];
[bottomText setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.2]];
[[self view]addSubview:bottomText];
[bottomText setText:[(SlideShowObj*)[_slideShow objectAtIndex:i-1]bottomText]];
[bottomText setTextAlignment:NSTextAlignmentCenter];
[bottomText setTextColor:[(SlideShowObj*)[_slideShow objectAtIndex:i-1]bottomTextColor]];
UIGraphicsBeginImageContext(_screenSize);
CGContextRef context = UIGraphicsGetCurrentContext();
[[[self view]layer] renderInContext:context];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
NSLog(#"%f,%f",theImage.size.width, theImage.size.height);
[_slideShowImageArray addObject:theImage];
UIGraphicsEndImageContext();
[bottomText removeFromSuperview];
[topText removeFromSuperview];
[imageView removeFromSuperview];
[bgImageView removeFromSuperview];
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
[self reload];
}
-(void)reload{
[_SlideImageView setFrame:CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, _screenSize.width, _screenSize.height)];
[_slideShow removeAllObjects];
[_slideShow removeAllObjects];
for (int i = 1; i<=8; i++) {
[_slideShow addObject:[self slideNumber:[NSNumber numberWithInt:i]]];
}
[self generateImages];
[self setSlideNumber:[NSNumber numberWithInt:1]];
[self begin];
}
The frame of your view hasn't been correctly set in viewDidLoad method, yet. It would be more accurate to move frame-size related code to viewWillAppear: method. Dimensions of the frame will be correct in viewWillAppear: or viewDidAppear: methods. Then, you may want to keep a boolean variable in order to generate images at the first appearance only.
Related
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];
}
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];
}
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
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.
I had an comments array, witch contains the comment message and the reply message and follow the reply message.want to show all the messages orderly, seems its An infinite loop.
My code is like below:
if (self.commentArray.count > 0) {
//comments
NSDictionary *message = [self.commentArray objectAtIndex:indexPath.row];
if ([FHWServiceManager isValidObject:[message objectForKey:#"UserIcon"]]) {
[cell.photoImageView setImageWithURL:[NSURL URLWithString:[message objectForKey:#"UserIcon"]] placeholderImage:[UIImage imageNamed:#"face_poor"]];
}else {
cell.photoImageView.image = [UIImage imageNamed:#"face_poor"];
}
cell.photoImageView.layer.cornerRadius = 15;
cell.photoImageView.layer.masksToBounds = YES;
cell.nameLabel.text = [message objectForKey:#"Username"];
cell.nameLabel.textColor = UIColorFromRGB(0xbf6327);
cell.contentLabel.text = [message objectForKey:#"Comment"];
cell.timeLabel.text = [DateUtil timePassedDescriptionFor:[DateUtil dateFromRFC3339DateString:[message objectForKey:#"CreateTime"]]];
//follow comment
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"PId == %d",[[message objectForKey:#"Id"] intValue]];
NSArray *tempArray = [self.replyCommentArray filteredArrayUsingPredicate:predicate];
if (tempArray.count > 0) {
UIImageView *triangleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(67, 80, 10, 5)];
triangleImageView.image = [UIImage imageNamed:#"comment_reply_arrow_top"];
[cell.contentView addSubview:triangleImageView];
UIView *followBackView = [[UIView alloc] initWithFrame:CGRectMake(55, 85, 245, tempArray.count * 21 + 10)];
followBackView.backgroundColor = UIColorFromRGB(0xf6f6f6);
followBackView.layer.cornerRadius = 5;
float lastHeight = 0.0;
for (int i = 0; i < tempArray.count; i ++) {
NSDictionary *replyMessage = [tempArray objectAtIndex:i];
NSString *replyStr;
replyStr = [NSString stringWithFormat:#"%#: %#",[replyMessage objectForKey:#"Username"],[replyMessage objectForKey:#"Comment"]];
TTTAttributedLabel *followCommentLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(5, lastHeight + 5, followBackView.frame.size.width, 21)];
// followCommentLabel.numberOfLines = 0;
followCommentLabel.font = [UIFont systemFontOfSize:13];
followCommentLabel.textColor = [UIColor darkGrayColor];
followCommentLabel.backgroundColor = [UIColor clearColor];
[followCommentLabel setText:replyStr afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange redColorRange = [[mutableAttributedString string] rangeOfString:[NSString stringWithFormat:#"%#:",[replyMessage objectForKey:#"Username"]] options:NSCaseInsensitiveSearch];
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
NSDictionary *colorDic = [NSDictionary dictionaryWithObjectsAndKeys:UIColorFromRGB(0xbf6327),kCTForegroundColorAttributeName, nil];
[mutableAttributedString addAttributes:colorDic range:redColorRange];
return mutableAttributedString;
}];
[followBackView addSubview:followCommentLabel];
UIButton *followButton = [UIButton buttonWithType:UIButtonTypeCustom];
followButton.frame = followCommentLabel.frame;
NSString *identify = [NSString stringWithFormat:#"%d",i];
[followButton setTitle:identify forState:UIControlStateSelected];
followButton.titleLabel.textColor = [UIColor clearColor];
[followButton addTarget:self action:#selector(handleFollowComment:) forControlEvents:UIControlEventTouchUpInside];
followButton.tag = indexPath.row + 10000;
[followBackView addSubview:followButton];
[followBackView bringSubviewToFront:followButton];
// CGSize size = [followCommentLabel.text sizeWithFont:followCommentLabel.font
// constrainedToSize:CGSizeMake(240, 800)
// lineBreakMode:NSLineBreakByWordWrapping];
// followCommentLabel.frame = CGRectMake(5, 0, 418, size.height);
predicate = [NSPredicate predicateWithFormat:#"PId == %d",[[replyMessage objectForKey:#"Id"] intValue]];
NSArray *subTempArray = [self.replyCommentArray filteredArrayUsingPredicate:predicate];
lastHeight += 21;
if (subTempArray.count > 0) {
lastHeight += subTempArray.count * 21;
float height = followBackView.frame.size.height;
height += 21*subTempArray.count;
followBackView.frame = CGRectMake(followBackView.frame.origin.x, followBackView.frame.origin.y, followBackView.frame.size.width, height);
float followLabelHeight = 0.0;
for (int j =0 ; j < subTempArray.count; j ++) {
NSDictionary *ohterMessage = [subTempArray objectAtIndex:j];
replyStr = [NSString stringWithFormat:#"%#reply%#: %#",[ohterMessage objectForKey:#"Username"],[replyMessage objectForKey:#"Username"],[ohterMessage objectForKey:#"Comment"]];
TTTAttributedLabel *subCommentLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(5, followCommentLabel.frame.origin.y + followCommentLabel.frame.size.height + followLabelHeight, followBackView.frame.size.width, 21)];
// subCommentLabel.numberOfLines = 0;
subCommentLabel.font = [UIFont systemFontOfSize:13];
subCommentLabel.textColor = [UIColor darkGrayColor];
subCommentLabel.backgroundColor = [UIColor clearColor];
[subCommentLabel setText:replyStr afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange redColorRange = [[mutableAttributedString string] rangeOfString:[NSString stringWithFormat:#"%#reply%#:",[ohterMessage objectForKey:#"Username"],[replyMessage objectForKey:#"Username"]] options:NSCaseInsensitiveSearch];
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
NSDictionary *colorDic = [NSDictionary dictionaryWithObjectsAndKeys:UIColorFromRGB(0xbf6327),kCTForegroundColorAttributeName, nil];
[mutableAttributedString addAttributes:colorDic range:redColorRange];
return mutableAttributedString;
}];
[followBackView addSubview:subCommentLabel];
UIButton *subfollowButton = [UIButton buttonWithType:UIButtonTypeCustom];
subfollowButton.frame = subCommentLabel.frame;
NSString *subIdentify = [NSString stringWithFormat:#"%d-%d",i,j];
[subfollowButton setTitle:subIdentify forState:UIControlStateSelected];
subfollowButton.titleLabel.textColor = [UIColor clearColor];
[subfollowButton addTarget:self action:#selector(handleFollowComment:) forControlEvents:UIControlEventTouchUpInside];
subfollowButton.tag = indexPath.row + 10000;
[followBackView addSubview:subfollowButton];
[followBackView bringSubviewToFront:subfollowButton];
// CGSize size = [followCommentLabel.text sizeWithFont:followCommentLabel.font
// constrainedToSize:CGSizeMake(240, 800)
// lineBreakMode:NSLineBreakByWordWrapping];
// followCommentLabel.frame = CGRectMake(5, 0, 418, size.height);
predicate = [NSPredicate predicateWithFormat:#"PId == %d",[[ohterMessage objectForKey:#"Id"] intValue]];
NSArray *subFollowTempArray = [self.replyCommentArray filteredArrayUsingPredicate:predicate];
followLabelHeight += 21;
if (subFollowTempArray.count > 0) {
followLabelHeight += subFollowTempArray.count * 21;
lastHeight += subFollowTempArray.count * 21;
float height = followBackView.frame.size.height;
height += 21*subFollowTempArray.count;
followBackView.frame = CGRectMake(followBackView.frame.origin.x, followBackView.frame.origin.y, followBackView.frame.size.width, height);
for (int k =0 ; k < subFollowTempArray.count; k ++) {
NSDictionary *ohterFollowMessage = [subFollowTempArray objectAtIndex:k];
NSString *replyFollowStr = [NSString stringWithFormat:#"%#reply%#: %#",[ohterFollowMessage objectForKey:#"Username"],[ohterMessage objectForKey:#"Username"],[ohterFollowMessage objectForKey:#"Comment"]];
TTTAttributedLabel *subFollowCommentLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(5, subCommentLabel.frame.origin.y + subCommentLabel.frame.size.height + k * 21, followBackView.frame.size.width, 21)];
// subCommentLabel.numberOfLines = 0;
subFollowCommentLabel.font = [UIFont systemFontOfSize:13];
subFollowCommentLabel.textColor = [UIColor darkGrayColor];
subFollowCommentLabel.backgroundColor = [UIColor clearColor];
[subFollowCommentLabel setText:replyFollowStr afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange redColorRange = [[mutableAttributedString string] rangeOfString:[NSString stringWithFormat:#"%#reply%#:",[ohterFollowMessage objectForKey:#"Username"],[ohterMessage objectForKey:#"Username"]] options:NSCaseInsensitiveSearch];
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
NSDictionary *colorDic = [NSDictionary dictionaryWithObjectsAndKeys:UIColorFromRGB(0xbf6327),kCTForegroundColorAttributeName, nil];
[mutableAttributedString addAttributes:colorDic range:redColorRange];
return mutableAttributedString;
}];
[followBackView addSubview:subFollowCommentLabel];
}
}
}
}
}
[cell.contentView addSubview:followBackView];
}
Try this, this may not be the exact solution. But you can follow this approach with some minor changes
- (NSArray *) replyforPid:(int) pID {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"PId == %d",pID];
NSArray *tempArray = [self.replyCommentArray filteredArrayUsingPredicate:predicate];
return tempArray;
}
- (void) addReplyInView:(UIView *) followBackView forPid:(int) pID lastHeight:(float) lastHeight {
NSArray *tempArray = [self replyforPid:pID];
if ([tempArray count] > 0) {
if (lastHeight != 0) {
float height = followBackView.frame.size.height;
height += 21*subTempArray.count;
followBackView.frame = CGRectMake(followBackView.frame.origin.x, followBackView.frame.origin.y, followBackView.frame.size.width, height);
}
for (int i = 0; i < tempArray.count; i ++) {
NSDictionary *replyMessage = [tempArray objectAtIndex:i];
NSString *replyStr;
replyStr = [NSString stringWithFormat:#"%#: %#",[replyMessage objectForKey:#"Username"],[replyMessage objectForKey:#"Comment"]];
TTTAttributedLabel *followCommentLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(5, lastHeight + 5, followBackView.frame.size.width, 21)];
followCommentLabel.font = [UIFont systemFontOfSize:13];
followCommentLabel.textColor = [UIColor darkGrayColor];
followCommentLabel.backgroundColor = [UIColor clearColor];
[followCommentLabel setText:replyStr afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange redColorRange = [[mutableAttributedString string] rangeOfString:[NSString stringWithFormat:#"%#:",[replyMessage objectForKey:#"Username"]] options:NSCaseInsensitiveSearch];
// Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
NSDictionary *colorDic = [NSDictionary dictionaryWithObjectsAndKeys:UIColorFromRGB(0xbf6327),kCTForegroundColorAttributeName, nil];
[mutableAttributedString addAttributes:colorDic range:redColorRange];
return mutableAttributedString;
}];
[followBackView addSubview:followCommentLabel];
UIButton *followButton = [UIButton buttonWithType:UIButtonTypeCustom];
followButton.frame = followCommentLabel.frame;
NSString *identify = [NSString stringWithFormat:#"%d",i];
[followButton setTitle:identify forState:UIControlStateSelected];
followButton.titleLabel.textColor = [UIColor clearColor];
[followButton addTarget:self action:#selector(handleFollowComment:) forControlEvents:UIControlEventTouchUpInside];
[followBackView addSubview:followButton];
[followBackView bringSubviewToFront:followButton];
lastHeight += 21;
[self addReplyInView:followBackView forPid:[[replyMessage objectForKey:#"Id"] intValue] lastHeight:lastHeight];
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.commentArray.count > 0) {
//comments
NSDictionary *message = [self.commentArray objectAtIndex:indexPath.row];
if ([FHWServiceManager isValidObject:[message objectForKey:#"UserIcon"]]) {
[cell.photoImageView setImageWithURL:[NSURL URLWithString:[message objectForKey:#"UserIcon"]] placeholderImage:[UIImage imageNamed:#"face_poor"]];
}else {
cell.photoImageView.image = [UIImage imageNamed:#"face_poor"];
}
cell.photoImageView.layer.cornerRadius = 15;
cell.photoImageView.layer.masksToBounds = YES;
cell.nameLabel.text = [message objectForKey:#"Username"];
cell.nameLabel.textColor = UIColorFromRGB(0xbf6327);
cell.contentLabel.text = [message objectForKey:#"Comment"];
cell.timeLabel.text = [DateUtil timePassedDescriptionFor:[DateUtil dateFromRFC3339DateString:[message objectForKey:#"CreateTime"]]];
//follow comment
NSArray *tempArray = [self replyforPid:[[message objectForKey:#"Id"] intValue]];
if (tempArray.count > 0) {
UIImageView *triangleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(67, 80, 10, 5)];
triangleImageView.image = [UIImage imageNamed:#"comment_reply_arrow_top"];
[cell.contentView addSubview:triangleImageView];
UIView *followBackView = [[UIView alloc] initWithFrame:CGRectMake(55, 85, 245, tempArray.count * 21 + 10)];
followBackView.backgroundColor = UIColorFromRGB(0xf6f6f6);
followBackView.layer.cornerRadius = 5;
[self addReplyInView:followBackView forPid:[[message objectForKey:#"Id"] intValue] intValue] lastHeight:0.0];
}
}
}