I used to have a massive packed 8k+ line FeedViewController and anytime I wanted to change anything involving the look of statuses I had to change no less than a dozen viewcontrllers so I decided to try to refactor to follow a MVC type standard. I put most of the functionality in the tableviewcells so that I could just change the cell class instead of 12 files, now im hearing "you should keep your VIEWS dumb.....is this really so wrong?
//
// TriCornerFeedCell.m
//
//
#import "NSDate+TimeAgo.h"
#import "TriCornerFeedCell.h"
#import "AFNetworking.h"
#implementation TriCornerFeedCell
-(void)refreshGestureRecognizers{
while (self.gestureRecognizers.count) {
[self removeGestureRecognizer:[self.gestureRecognizers objectAtIndex:0]];
}
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(processDoubleTap:)];
doubleTap.numberOfTapsRequired = 2;
[self addGestureRecognizer:doubleTap];
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.3; //seconds
lpgr.delegate = self;
[self addGestureRecognizer:lpgr];
}
-(void)refreshCell{
_sdmanager = [SDWebImageManager sharedManager];
//Set Name Label
self.NameLabel.text=[NSString stringWithFormat:#"%# %#",self.statusObject.first_name,self.statusObject.last_name];
//Set Message Label
if(self.statusObject.message!=nil){
self.StatusLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
self.StatusLabel.text = self.statusObject.message;
self.StatusLabel.delegate = self;
[self checkForShoutoutsAndHashtags];
self.StatusLabel.lineBreakMode=0;
self.StatusLabel.numberOfLines=0;
//Cell.StatusLabel.text=[tempDictionary objectForKey:#"message"];
[self.StatusLabel sizeToFit];
}
//Set Date Label
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:self.statusObject.created];
self.timeLabel.text=[date timeAgo];
//Set Bump Views
if(self.statusObject.isBumped){
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_yellow.png"] forState:UIControlStateNormal];
}else{
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_grey.png"] forState:UIControlStateNormal];
}
self.bumpCount.text=[#(self.statusObject.bump_count) stringValue];
[self.bumpClearViewBtn addTarget:self action:#selector(bump:) forControlEvents:UIControlEventTouchUpInside];
[self.bumpCornerBG addTarget:self action:#selector(bump:) forControlEvents:UIControlEventTouchUpInside];
//Set Comment Related Views
if(self.statusObject.comment_count>0){
NSLog(#"COMMENT_COUNT:%d",self.statusObject.comment_count);
[self.commentCount setHidden:NO];
[self.miniCommentColorCircle setHidden:NO];
self.commentCount.text=[#(self.statusObject.comment_count) stringValue];
}else{
[self.commentCount setHidden:YES];
[self.miniCommentColorCircle setHidden:YES];
}
//Set Follow Btn Views
[self.followBtn.titleLabel setFont:[UIFont fontWithName:#"BloggerSans" size:14]];
[self.followBtn removeFromSuperview];
if(!self.statusObject.isFollowing){
[self.followBtn removeFromSuperview];
UIButton *followBtn= [[UIButton alloc] initWithFrame:CGRectMake(235, 16, 75, 25)];
[followBtn setImage:nil forState:UIControlStateNormal];
followBtn.layer.cornerRadius =2; // this value vary as per your desire
[followBtn.titleLabel setFont:[UIFont fontWithName:#"BloggerSans" size:14.0f]];
followBtn.titleEdgeInsets = UIEdgeInsetsMake(3, 0, 0, 0);
followBtn.clipsToBounds = YES;
[followBtn setTitleColor:[self colorWithHexString:#"ff68a8"] forState:UIControlStateNormal];
followBtn.layer.borderWidth=1.5f;
followBtn.layer.borderColor=[[self colorWithHexString:#"ff68a8"] CGColor];
[followBtn setTitle:#"Follow" forState:UIControlStateNormal];
[followBtn addTarget:self action:#selector(follow) forControlEvents:UIControlEventTouchUpInside];
self.followBtn=followBtn;
[self addSubview:self.followBtn];
}
//Reset icon to default in case default==nill
[self bringSubviewToFront:self.DefaultImgBorder];
[self bringSubviewToFront:self.DefaultImgBtn];
UIImage *noDefault = [UIImage imageNamed:#"female_mini_no_default_icon.png"];
[self.DefaultImgBtn setBackgroundImage:noDefault forState:UIControlStateNormal];
//Attempt to create hexagon cropped default photo
UIImage *hex_img = [UIImage imageNamed:#"big_hex_thumb.png"];
UIImage *tan=[UIImage imageNamed:#"feed_grey.png"];
UIImage *finalBG= [self maskImage:tan withMask:hex_img];
[self.DefaultImgBorder setImage:finalBG];
NSURL *thumb_url=[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",s3thumbURL,self.statusObject.thumb_img]];
#autoreleasepool {
[_sdmanager downloadWithURL:thumb_url
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize){}completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished){
if (image)
{
UIImage *thumbimg = image;
UIImage *hex_img = [UIImage imageNamed:#"big_hex_thumb.png"];
UIImage *noDefault = [UIImage imageNamed:#"female_mini_no_default_icon.png"];
[self.DefaultImgBtn setBackgroundImage:noDefault forState:UIControlStateNormal];
UIImage *finalImg= [self maskImage:thumbimg withMask:hex_img];
[self.DefaultImgBtn setBackgroundImage:finalImg forState:UIControlStateNormal ];
}
}];
}
[self.DefaultImgBtn removeTarget:nil
action:NULL
forControlEvents:UIControlEventAllEvents];
[self.DefaultImgBtn addTarget:self action:#selector(viewProfile:) forControlEvents:UIControlEventTouchUpInside];
//Misc Stuff
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
}
#pragma mark - Interaction Methods
-(void)follow{
[self.followSpinner removeFromSuperview];
[self.followBtn removeFromSuperview];
self.followSpinner = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStyleFadingCircleAlt color: [self colorWithHexString:#"b4b4b2"] spinnerSize:25];
[self.followSpinner setFrame:CGRectMake(260,15,30,30)];
self.spinner.tag=9;
[self addSubview:self.followSpinner];
[self.statusObject follow];
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (self.indexPath != nil && gestureRecognizer.state == UIGestureRecognizerStateBegan) {
NSString*loggedin_uid = [[NSUserDefaults standardUserDefaults] objectForKey:#"uid"];
if([self.statusObject.IMPORT_SOURCE isEqualToString:#"INSTAGRAM"] || [self.statusObject.IMPORT_SOURCE isEqualToString:#"TWITTER"]){
if([loggedin_uid isEqualToString:#"1"] || [loggedin_uid isEqualToString:#"2"]){
[self.delegate showImportAdminControls:self.indexPath];
}
}else{
if([loggedin_uid isEqualToString:#"1"] || [loggedin_uid isEqualToString:#"2"]){
[self.delegate showAdminControls:self.indexPath];
}else if ([self.statusObject.uid isEqualToString:loggedin_uid]){
[self.delegate deletePostAlert:self.indexPath];
}
}
}
}
- (void) processDoubleTap:(UITapGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateEnded)
{
if (self.indexPath)
{
self.statusObject.indexPath=self.indexPath;
if(!self.statusObject.isBumped){
int value = self.statusObject.bump_count+1;
self.statusObject.isBumped=YES;
self.statusObject.bump_count=value;
[self.bumpCount setText:[#(value) stringValue]];
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_yellow.png"] forState:UIControlStateNormal];
UIImageView *bumpBlowUpIcon=[[UIImageView alloc]initWithFrame:CGRectMake((self.frame.size.width/2)-5, (self.frame.size.height/2)-5, 10, 10)];
[bumpBlowUpIcon setImage:[UIImage imageNamed:#"heart_yellow.png"]];
bumpBlowUpIcon.alpha=.2;
[self addSubview:bumpBlowUpIcon];
[UIView animateWithDuration:.8 delay:0 usingSpringWithDamping:.3 initialSpringVelocity:.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
[bumpBlowUpIcon setFrame:CGRectMake((self.frame.size.width/2)-(self.frame.size.height/2), 0, self.frame.size.height, self.frame.size.height)];
bumpBlowUpIcon.alpha=.5;
}completion:^(BOOL finished) {
[bumpBlowUpIcon removeFromSuperview];
}];
}else{
int value = self.statusObject.bump_count-1;
self.statusObject.isBumped=NO;
self.statusObject.bump_count=value;
[self.bumpCount setText:[#(value) stringValue]];
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_grey.png"] forState:UIControlStateNormal];
}
[self.statusObject bump];
}
}
}
-(void)viewProfile{
}
-(void)viewHashtag{
}
#pragma mark - Misc Methods
- (UIImage*) maskImage:(UIImage *) image withMask:(UIImage *) mask
{
CGImageRef imageReference = image.CGImage;
CGImageRef maskReference = mask.CGImage;
CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskReference),
CGImageGetHeight(maskReference),
CGImageGetBitsPerComponent(maskReference),
CGImageGetBitsPerPixel(maskReference),
CGImageGetBytesPerRow(maskReference),
CGImageGetDataProvider(maskReference),
NULL, // Decode is null
YES // Should interpolate
);
CGImageRef maskedReference = CGImageCreateWithMask(imageReference, imageMask);
CGImageRelease(imageMask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedReference];
CGImageRelease(maskedReference);
return maskedImage;
}
-(UIColor*)colorWithHexString:(NSString*)hex
{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];
// strip 0X if it appears
if ([cString hasPrefix:#"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor grayColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
#end
Ok. I've tried to merge all comments to a suitable answer.
When you want to stick to the MVC pattern you should keep your views as dumb as possible (regarding the coupling of view- and business-related components). In the best case they should not contain any business logic.
That implies that they also should not know anything about business objects (the model). As long as your statusObject in self.StatusLabel.text = self.statusObject.message; is anything else than a Data Transfer Object it is not a good idea to let the cells retrieve their values on their own - because then these cells would need to have knowledge about your model structure.
Usually each view does have its own view controller but - of course - you're allowed to compose your view controllers with functionality they need.
For example: if some view controllers need data you could introduce a separate (view related) component which will provide that data (e.g. by creating and returning cells). This component would be fed with your model data (or Data Transfer Objects) and would return a structure which could be used by all view controllers who need those information.
Related
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];
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I implement scroll view to horizontally scroll the view pages loaded from a NSDictionary. Presently i am using swipegesture but that is little slow.
What code should I implement to achieve horizontal scrolling?
i am using this code:
-(void)DownLoadData:(NSString *)indexSelect
{
{
[[SharedUtilities getInstance]AddActivityIndicatorViewOnMainThread:self.view];
}
self._parserForNewsDetail = [afaqsParser getInstance];
[[afaqsParser getInstance] setCacheNeed:TRUE];
[self._parserForNewsDetail parseWithUrl:[_arrUrlLinks objectAtIndex:[indexSelect integerValue]] UrlTypefor:nil];
NSDictionary *resultDic;
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSLog(#"Detail Dic = %#",[resultDic description]);
if (resultDic== NULL || resultDic ==nil)
{
//Check internet here
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
[SharedUtilities ShowAlert:#"No Data Found" title:nil withView:self.view];
return;
}
[self performSelectorOnMainThread:#selector(SetValuesInUserInterface:) withObject: resultDic waitUntilDone:NO];
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
}
-(void)SetValuesInUserInterface:(NSDictionary *)Dic
{
self._imageView1.layer.cornerRadius = 4;
self._imageView1.clipsToBounds = YES;
self._imageView1.tag = 999;
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
[[subviewsArr objectAtIndex:i] removeFromSuperview];
}
}
if ([[Dic valueForKey:#"image"] isEqual:#""])
{
// strg=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"image"]];
_imageView1.hidden=YES;
// _txtView.frame=CGRectMake(4.0f,95.0f,310.0f,100.0f );
_txtView.frame=CGRectMake(4.0f,95.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"NO IMAGE");
}
else{
_imageView1.hidden=NO;
_imageView1.frame=CGRectMake(4.0f,95.0f,310.0f,180.0f );
_txtView.frame=CGRectMake(4.0f,316.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"IMAGE VISIBLE");
}
self._scrollView.scrollEnabled = YES;
self._scrollView.showsVerticalScrollIndicator = YES;
self._scrollView.showsHorizontalScrollIndicator = YES;
self._header.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:18];
[self._header setText: [Dic valueForKey:#"header"]];
self._header.textColor=[UIColor blackColor];
[self._publicationDate setText:[Dic valueForKey:#"PUB_DATE"]];
[self._kicker setText:[Dic valueForKey:#"kicker"]];
[self._txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
NSString *writer;
if ([[Dic valueForKey:#"AUTHOR"] length]>2)
{
writer=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"AUTHOR"]];
}
else
{
writer=#"";
}
NSString *city;
if ([[Dic valueForKey:#"REPORTING_CITY"] length]>2)
{
city=[NSString stringWithFormat:#", %#",[Dic valueForKey:#"REPORTING_CITY"]];
}
else
{
city=#"";
}
NSString *str = [NSString stringWithFormat:#"%#ee%#", writer,city];
//[cell._Writer setText: [tempDic valueForKey:#"writer"]];
[self._Writer setText:str];
[_txtView sizeToFit]; //added
[_txtView layoutIfNeeded]; //added
CGRect frame = self._txtView.frame;
self._txtView.frame = frame;
[_txtView setScrollEnabled:NO];
self._scrollView.contentSize = CGSizeMake(320,440+frame.size.height);
_titleLabel.frame= CGRectMake(0, self._scrollView.contentSize.height-119, [[UIScreen mainScreen] bounds].size.width, 40);
_titleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_titleLabel.font = [UIFont fontWithName:#"Helvetica" size:13.5];
_titleLabel.numberOfLines=2;
[self._scrollView addSubview:_titleLabel];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_titleLabel = [[UILabel alloc] init];
lblTitle.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:20];
lblTitle.text=_strTitle;
NSLog(#"arrUrls %d",[_arrUrlLinks count]);
NSLog(#"strCurrentNewsSelect %#",_strCurrentNewsSelect);
[[NSNotificationCenter defaultCenter]
postNotificationName:#"DISABLEGESTURE"
object:self];
count=[_strCurrentNewsSelect integerValue];
[self performSelectorInBackground:#selector(DownLoadData:) withObject:_strCurrentNewsSelect];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
}
_lblNewsCount.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:16];
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",[_strCurrentNewsSelect integerValue]+1,[_arrUrlLinks count]];
// Do any additional setup after loading the view from its nib.
UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(280, 340, 40, 40)];
[shareBtn addTarget:self action:#selector(Share:) forControlEvents:UIControlEventTouchUpInside];
[shareBtn setBackgroundImage:[UIImage imageNamed:#"share1.png"] forState:UIControlStateNormal];
// [self.view addSubview:shareBtn];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
}
if([_strCurrentNewsSelect isEqualToString:[NSString stringWithFormat:#"%d",[_arrUrlLinks count]-1]])
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(rightSwipeHandle:)];
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[rightRecognizer setNumberOfTouchesRequired:1];
//add the your gestureRecognizer , where to detect the touch..
[_scrollView addGestureRecognizer:rightRecognizer];
UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(leftSwipeHandle:)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
}
-(IBAction)Share:(UIButton *)sender
{
NSLog(#"SHare called =%d",sender.tag);
// NSDictionary *tempDic = [[self._resultDic valueForKey:#"items"] objectAtIndex:sender.tag];
[[SharedUtilities getInstance] set_LinkForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"image"]];
[[SharedUtilities getInstance]set_headerForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"header"]];
[[SharedUtilities getInstance]set_viewController:self];
[[SharedUtilities getInstance]Share];
}
-(IBAction)btnBackPress:(id)sender;
{
[[NSNotificationCenter defaultCenter]
postNotificationName:#"ENABLEGESTURE"
object:self];
[self.navigationController popViewControllerAnimated:YES];
lblTitle.text=_strTitle;
}
-(IBAction)btnNextClick
{
btnPreviousNews.userInteractionEnabled=TRUE;
if(count!=[_arrUrlLinks count] -1)
{
if(count==[_arrUrlLinks count]-2)
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
count=count +1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"next %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
else{
btnNextNews.userInteractionEnabled=FALSE;
}
}
-(IBAction)btnPreviousClick
{
btnNextNews.userInteractionEnabled=TRUE;
if(count==0)
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
if(count==1)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
[btnNextNews setImage:[UIImage imageNamed:#"arrow1_next.png"] forState:UIControlStateNormal];
count=count-1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"previous %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
}
}
Have you tried as like below methods,
UIScrollView * _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 10.0, 320.0, 280.0)];
_scrollView.backgroundColor = [UIColor clearColor];
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
[self addSubview:_scrollView];
float width = 0.0;
for (int i = 0; i < pageCount; i++)
{
UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake((i * 320.0) + 20.0, 0.0, 280.0, 280.0);
[_scrollView addSubview:yourView];
width = yourView.frame.size.width + yourView.frame.origin.x + 20.0;
}
[_scrollView setContentSize:CGSizeMake(width, _scrollView.frame.size.height)];
Look at UIScrollView. To be honest this question makes it look like you've done very little research into the problem though. Can you tell us a bit more about what you currently have and what you've done so far?
UIScrollView Scroll depends on the ContentSize. So you have to set the ContentSize.
For Horizinatal Scrolling
[scroll setContentSize:CGSizeMake(1500, scroll.frame.size.height)];
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 am having a table view with custom cells. Each custom cell is having scroll view in which images are added in series. Images are of quite large size. Other than images, some other datas are also present in each cell. I am saving the images to db before reloading table view.The issue is as the tableview reloaddata is calling continuously and my scroll view inside the cell is not working properly. What is the efficient method for reloading table view without affecting the scroll inside.Images should also load in a proper manner.
this is how i m calling those methods:
-(void)viewWillAppear:(BOOL)animated{
[self performSelectorInBackground:#selector(getPacksdetails) withObject:nil];}
-(void) getPacksdetails
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
ForcePackRequest *request = [[ForcePackRequest alloc] init];
User *userObj = (User *)[request getActiveUser];
NSString *emailString =[NSString stringWithFormat:#"%#", userObj.Email ];
BOOL isPackList= [request getPurchasedPacksOfUser:emailString toArray:packsListArray excerciseArray:excercisesArray recommendedGearsArray:recommendedGears];
// NSMutableArray *namesArray=[[NSMutableArray alloc]init];
for(int packscounter=0;packscounter<[packsListArray count];packscounter++){
if([[[packsListArray objectAtIndex:packscounter]objectForKey:#"name"] isEqualToString: passedPackName]){
//nslog(#"passedPackName%#",passedPackName);
////nslog(#"%#",data.exName);
reservedIndexPath=nil;
reservedIndexPath= [NSIndexPath indexPathForRow:0 inSection:packscounter];
//nslog(#"%#",reservedIndexPath);;
break;
}
// reservedIndexPath=[NSIndexPath indexPathWithIndex:i];
}
if(isPackList)
[self performSelectorInBackground:#selector(loadExerthumbThread:) withObject:nil];
}
- (void) loadExerthumbThread:(id)sender{
//if (FP_DEBUG) //nslog(#"%#",excercisesArray);
for(int i=0;i<[excercisesArray count];i++){
NSMutableArray *exforAsection=[[NSMutableArray alloc]init];
// exerciseArrayForeachSection=[excercisesArray objectAtIndex:i];
exforAsection=[excercisesArray objectAtIndex:i];
for (int intConter = 0; intConter <[exforAsection count]; intConter++)
{
Exercise *data = [exforAsection objectAtIndex:intConter];
// NSString *imageName = [[data.exImage ] intValue];
int intExerId = [data.exImage intValue];
NSString *imagestr = [NSString stringWithFormat:#"hires_%d",intExerId];
FileManager *objFileManager = [[FileManager alloc] init];
NSData *imageData = nil;
if ([objFileManager isFileExistsInDocDir:imagestr])
{
imageData = [objFileManager getFileFormDocDirWithName:imagestr];
}
else
{
NSString *imageUrlString = [NSString stringWithFormat:#"http://www.forcetherex.com/force_uploads/exercise/exercise_hires/%#.png",data.exId];
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
if (data != nil)
{
if ([data length] > 100)
imageData = [data copy];
}
if (imageData != nil){
[objFileManager writeFileToAppDirectoryWithFileName:imagestr andFileData:imageData];
//Mark as dont back up
NSURL *fileUrl = [NSURL fileURLWithPath:imagestr];
[self addSkipBackupAttributeToItemAtURL:fileUrl];
fileUrl=nil;
data = nil;
}
}
if (imageData != nil)
data.exThumbImage = imageData;
objFileManager = nil;
}
[self reloadTableView];
}
and my cellforrow atindexpath code is:
{
NSString *CellIdentifier = [NSString stringWithFormat:#"%d_%d",indexPath.section,indexPath.row];
//static NSString *CellIdentifier = #"CustomCellFor_Dashboard";
_customCell = (CustomCellFor_Dashboard *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (_customCell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCellFor_Dashboard" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
_customCell = (CustomCellFor_Dashboard *) currentObject;
_customCell.delegate=self;
break;
}
}
}
_customCell.exNameDictArray=[[packsListArray objectAtIndex:indexPath.section]objectForKey:#"exerciseList"];
_customCell.indexPath=indexPath;
NSLog(#"%d",sng.showingPath.section);
if(indexPath.section ==sng.showingPath.section)
_customCell.exnameTable.hidden=FALSE;
sectionInt=indexPath.section;
exerciseArrayForeachSection=[[NSMutableArray alloc]init];
//[exerciseArrayForeachSection removeAllObjects];
exerciseArrayForeachSection=[excercisesArray objectAtIndex:indexPath.section];
//next btn
UIButton *accessoryView = [[UIButton alloc] initWithFrame: _customCell.nextBtn.frame];
accessoryView.tag = indexPath.section;
[accessoryView setImage:[imageasArr objectAtIndex:0]forState:UIControlStateNormal];
[accessoryView addTarget:self action:#selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[_customCell addSubview:accessoryView];
//_customCell.accessoryView = accessoryView;
//prev btn
UIButton *prevBtn = [[UIButton alloc] initWithFrame: _customCell.prevBtn.frame];
prevBtn.tag = indexPath.section;
[prevBtn setImage:[imageasArr objectAtIndex:2]forState:UIControlStateNormal];
[prevBtn addTarget:self action:#selector(previousButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[_customCell addSubview:prevBtn];
_customCell.selectionStyle = UITableViewCellSelectionStyleNone;
[_customCell addSubview:_customCell.buttonView];
_customCell.nameLabel.text=[[packsListArray objectAtIndex:indexPath.section]objectForKey:#"name"];
_customCell.exCountLbl.text=[NSString stringWithFormat:#"%#", [[packsListArray objectAtIndex:indexPath.section]objectForKey:#"exercises"]];
_customCell.scroll.delegate = self;
// [_customCell.scroll setBackgroundColor:[UIColor blackColor]];
[_customCell.scroll setCanCancelContentTouches:NO];
_customCell.scroll.indicatorStyle = UIScrollViewIndicatorStyleWhite;
_customCell.scroll.clipsToBounds = YES;
[_customCell.scroll setContentOffset:CGPointMake(0, 20)];
if([exerciseArrayForeachSection count]>0){
_customCell. scroll.frame = CGRectMake(0,40, 320, _customCell.scroll.frame.size.height-10);
_customCell. scroll.contentSize = CGSizeMake(320*[exerciseArrayForeachSection count],_customCell .scroll.frame.size.height);
int cx = 30;
for(int i=0;i<[exerciseArrayForeachSection count];i++){
Exercise *data = [exerciseArrayForeachSection objectAtIndex:i];
UIView *detailView=[[UIView alloc]initWithFrame:_customCell.excerciseDetailsView.frame];
UILabel *titleLbl=[[UILabel alloc]initWithFrame:_customCell.exTitleLabel.frame];
titleLbl.font=[UIFont systemFontOfSize:12];
UIImageView *exerciseImg=[[UIImageView alloc]initWithFrame: _customCell.exThumbImageView.frame];
UIButton *playBtn=[[UIButton alloc]initWithFrame:_customCell.exThumbButton.frame];
playBtn.showsTouchWhenHighlighted=YES;
[playBtn setImage:[imageasArr objectAtIndex:1]forState:UIControlStateNormal];
// playBtn.frame =_customCell.exThumbButton.frame;
playBtn.tag=i;
[playBtn addTarget:self action:#selector(videoPlayActn:) forControlEvents:UIControlEventTouchUpInside];
[titleLbl setText:data.exName];
if ([data.exThumbImage length] > 0)
[exerciseImg setImage:[UIImage imageWithData:data.exThumbImage]];
[detailView addSubview:titleLbl];
[exerciseImg addSubview: playBtn];
[detailView addSubview:exerciseImg];
// _customCell.exThumbButton= playBtn;
[exerciseImg bringSubviewToFront:playBtn];
exerciseImg.userInteractionEnabled=TRUE;
[detailView bringSubviewToFront:playBtn];
//if (FP_DEBUG) //nslog(#"%f",_customCell.scroll.frame.origin.x);
detailView.frame=CGRectMake(cx, 30, 320, _customCell.scroll.contentSize.height);
//_customCell.exThumbImageView=exerciseImg;
[_customCell.scroll addSubview:detailView];
detailView=nil;
exerciseImg=nil;
titleLbl=nil;
_customCell.scroll.contentSize = CGSizeMake( cx,_customCell.scroll.contentSize.height);
cx = cx+_customCell.scroll.frame.size.width;
//if (FP_DEBUG) //nslog(#"%i",cx);
}
}
// [_customCell.scroll setContentOffset:CGPointMake(0, 20)];
//if (FP_DEBUG) //nslog(#"%f",_customCell.scroll.contentOffset.x);
[_customCell.howyoulfeelBtn addTarget:self action:#selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
[_customCell.expertAdviceBtn addTarget:self action:#selector(expertbuttonclicked:) forControlEvents:UIControlEventTouchUpInside];
[_customCell.recoverTrackerBtn addTarget:self action:#selector(recoverytrackerBtnclicked:) forControlEvents:UIControlEventTouchUpInside];
[_customCell.recommendedGearsBtn addTarget:self action:#selector(recommendedGearsBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
////nslog(#"ewfewr************ewr");
if(indexPath.section== expandViewclickedSection&&_isexpanded==TRUE){
_customCell.scroll.frame = CGRectMake(-160, 22, self.view.frame.size.width, self.view.frame.size.height);
_customCell.shareView.hidden=FALSE;
// _customCell.nextBtn.hidden=TRUE;
accessoryView.hidden=TRUE;
//_isexpanded=TRUE;
}
else if(indexPath.section== expandViewCollapsedSection&&_isexpanded==FALSE) {
_customCell.scroll.frame = CGRectMake(-0, 22, self.view.frame.size.width, self.view.frame.size.height);
_customCell.shareView.hidden=TRUE;
// _isexpanded=FALSE;
}
if(_isExListingTablePresented==TRUE&&indexPath.section==exlistTableAddedSection){
_customCell.exListingTable.hidden=FALSE;
}
else if(_isExListingTablePresented==FALSE&&indexPath.section==_exlistTableremovedSection){
_customCell.exListingTable.hidden=TRUE;
}
return _customCell;
}
First of all shift all the code related to the DB/IO calls to another controller and make async calls to that and return the result by means to delegate methods (or anything else you deem fit). That would improve the overall performance of your code, and the scroll view would work fine.
In case that does not make things perfect, place the DB/IO calls inside a new thread, that'll ensure that your scroll view (and your app overall) performs fine.
You should update UI in the main thread.
[self performSelectorOnMainThread:reloadTableView withObject:nil waitUntilDone:NO];
You shouldn't reload table in such high Frequency, this will slow down your app if there are too much contents in the cells. Try reload table after all data updated. Of source, data updating should run in background threads.
I see you set the cell indentifier with row and section number, so you can do some tricks with it. Like comparing the image urls to decide whether setImage (this will cost lots of performance) or not.
Good afternoon. I use in my application iCarousel . At the moment I can not make Progress View each item carousel. The problem is that when I click on the "Download button" Progress View have added an item first . He appears fine and works , but also appears in another 2 item from another view, where it should not be . After that, when I again click the " download button " Progress View begin to be confused with each other. Please tell me exactly what I 'm doing wrong and how I act of intercourse ? I'm new to objective-c.
P.S To download the data I use AFNetworking.
iCarousel:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Caches"];
NSDictionary *myDic =[magazinesInfo objectAtIndex:index];
//Change image size
UIImage *img = [UIImage imageWithImage:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#_img.png",docDir,[myDic objectForKey:#"title"]]] scaledToSize:CGSizeMake(370,513)];
UIImageView *faceImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,768,1004)];
UIImage *dwImage = [UIImage imageNamed:#"button.png"];
UIImage *readImage = [UIImage imageNamed:#"read_button.png"];
UIImage *deleteImage = [UIImage imageNamed:#"delete_button.png"];
UIImage *cancelImage = [UIImage imageNamed:#"cancelButton.png"];
if(view ==nil)
{
UILabel *nomer = [[UILabel alloc] initWithFrame:CGRectMake(345, 85+MY_OFFSET, 75, 29)];
UILabel *nameMag = [[UILabel alloc] initWithFrame:CGRectMake(55, 720+MY_OFFSET, 658, 80)];
UILabel *dateMag = [[UILabel alloc] initWithFrame:CGRectMake(55, 821+MY_OFFSET, 658, 23)];
UIButton *downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(321, 890+MY_OFFSET, 128, 37)];
UIButton *readButton = [[UIButton alloc] initWithFrame:CGRectMake(246, 890+MY_OFFSET, 128, 37)];
UIButton *deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(385, 890+MY_OFFSET, 128, 37)];
UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0+MY_OFFSET, 128, 37)];
view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 768, 1004)];
view = faceImage;
faceImage.image = nil;
((UIImageView *)view).image = nil;
view.contentMode = UIViewContentModeCenter;
//Magazine number
nomer.backgroundColor = [UIColor clearColor];
nomer.textAlignment = NSTextAlignmentCenter;
[nomer setFont:[UIFont fontWithName:#"OpenSans-Light" size:36.0f]];
nomer.textColor = [UIColor whiteColor];
nomer.tag = 1;
//Magazine name
nameMag.backgroundColor = [UIColor clearColor];
nameMag.textAlignment = NSTextAlignmentCenter;
[nameMag setFont:[UIFont fontWithName:#"OpenSans-Light" size:30.0f]];
nameMag.numberOfLines=2 ;
nameMag.textColor = [UIColor blackColor];
nameMag.tag = 3;
//Date magazine
dateMag.backgroundColor = [UIColor clearColor];
dateMag.textAlignment = NSTextAlignmentCenter;
[dateMag setFont:[UIFont fontWithName:#"OpenSans-Light" size:20.0f]];
dateMag.textColor = [UIColor blackColor];
dateMag.tag = 4;
//Download button
[downloadButton setBackgroundImage:dwImage forState:UIControlStateNormal];
[downloadButton addTarget:self action:#selector(pressDownload:) forControlEvents:UIControlEventTouchUpInside];
downloadButton.tag = 5;
downloadButton.hidden = YES;
//Read button
[readButton setBackgroundImage:readImage forState:UIControlStateNormal];
[readButton addTarget:self action:#selector(readMag:) forControlEvents:UIControlEventTouchUpInside];
readButton.hidden=YES;
readButton.tag = 8;
//Delete button
[deleteButton setBackgroundImage:deleteImage forState:UIControlStateNormal];
[deleteButton addTarget:self action:#selector(deleteMag:) forControlEvents:UIControlEventTouchUpInside];
deleteButton.hidden=YES;
deleteButton.tag = 9;
[cancelButton setBackgroundImage:cancelImage forState:UIControlStateNormal];
[cancelButton addTarget:self action:#selector(deleteMag:) forControlEvents:UIControlEventTouchUpInside];
cancelButton.hidden=NO;
cancelButton.tag = 10;
//Add label to view
[view addSubview:nomer];
[view addSubview:nameMag];
[view addSubview:dateMag];
//Add button to view
[view addSubview:downloadButton];
[view addSubview:readButton];
[view addSubview:deleteButton];
[view addSubview:cancelButton];
}
else
{
//Set tag to image
((UIImageView *)faceImage).image = (UIImage*)[view viewWithTag:2];
//Set tag to label
[[[view subviews]objectAtIndex:0]viewWithTag:1];
[[[view subviews]objectAtIndex:1]viewWithTag:3];
[[[view subviews]objectAtIndex:2]viewWithTag:4];
//Set tag to button
[[[view subviews]objectAtIndex:3]viewWithTag:5];
[[[view subviews]objectAtIndex:4]viewWithTag:8];
[[[view subviews]objectAtIndex:5]viewWithTag:9];
[[[view subviews]objectAtIndex:6]viewWithTag:10];
}
//Hide button download and show read,delete button
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[NSString stringWithFormat:#"%#/%#_mag.pdf",docDir,[myDic objectForKey:#"title"]]] == YES)
{
[[[view subviews] objectAtIndex:4] setHidden:NO];
[[[view subviews] objectAtIndex:5] setHidden:NO];
[[[view subviews] objectAtIndex:3] setHidden:YES];
}
else
{
[[[view subviews] objectAtIndex:4] setHidden:YES];
[[[view subviews] objectAtIndex:5] setHidden:YES];
[[[view subviews] objectAtIndex:3] setHidden:NO];
}
//Hide date and name of magazine when view changed
if (index != [self.carousel currentItemIndex]) {
[[[view subviews]objectAtIndex:1]setHidden:YES];
[[[view subviews]objectAtIndex:2]setHidden:YES];
}
else{
[[[view subviews]objectAtIndex:1]setHidden:NO];
[[[view subviews]objectAtIndex:2]setHidden:NO];
}
((UIImageView *)view).image = img;
UILabel *nomer = [[view subviews]objectAtIndex:0];
nomer.text = [myDic objectForKey:#"title"];
UILabel *nameMag = [[view subviews]objectAtIndex:1];
nameMag.text = #"Жить интересно!” №5 Путешествия как стиль жизни";
UILabel *dateMag = [[view subviews]objectAtIndex:2];
dateMag.text = [myDic objectForKey:#"date"];
return view;
}
Download button action:
- (IBAction)pressDownload:(id)sender
{
NSLog(#"download button was pressed");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary *myDic = [magazinesInfo objectAtIndex:curID];
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Caches"];
NSString *pdfFilePath = [NSString stringWithFormat:#"%#/%#_mag.pdf.tmp",docDir,[myDic objectForKey:#"title"]];
NSString *newPdfNamePath = [NSString stringWithFormat:#"%#/%#_mag.pdf",docDir,[myDic objectForKey:#"title"]];
//Test for Progress bar
UIButton *pressedButton = (UIButton *)sender;
UIView *superViewOfPressedButton = pressedButton.superview;
UIProgressView *downloadProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(300, 950, 127, 8)];
UILabel *downloadPrecent = [[UILabel alloc]initWithFrame:CGRectMake(430, 950, 60, 20)];
[superViewOfPressedButton addSubview:downloadProgress];
[superViewOfPressedButton addSubview:downloadPrecent];
[downloadProgress setHidden:NO];
[downloadPrecent setHidden:NO];
NSLog(#"%#",sender);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[myDic objectForKey:#"magazine"]]];
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:pdfFilePath append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
downloadProgress.progress = (float)totalBytesRead / totalBytesExpectedToRead;
downloadPrecent.text =[NSString stringWithFormat:#"%1.0f%# ",((float)totalBytesRead / totalBytesExpectedToRead)*100,#"%"];
}];
[operation setCompletionBlock:^{
[fileManager moveItemAtPath:pdfFilePath toPath:newPdfNamePath error:NULL];
[fileManager removeItemAtPath:[NSString stringWithFormat:#"%#/%#_mag.pdf.tmp",docDir,[myDic objectForKey:#"title"]] error:NULL];
[downloadProgress setHidden:YES];
[downloadPrecent setHidden:YES];
NSLog(#"downloadComplete!");
[carousel reloadData];
}];
[operation start];
}
To Wain:
Sorry but I can not understand your question. I pass the URL from the dictionary in the method of downloading data. In Method iCarousel I assign Progress View tag = 7 then I add a condition to hide like this:
if (([fileManager fileExistsAtPath:[NSString stringWithFormat:#"%#/%#_mag.pdf.tmp",docDir,[myDic objectForKey:#"title"]]] == YES) && (index == [self.carousel currentItemIndex]))
{
[[[view viewWithTag:7] setHidden:NO];
[[[view viewWithTag:7] setHidden:NO];
}
else
{
[[[view viewWithTag:7] setHidden:YES];
[[[view viewWithTag:7] setHidden:YES];
}
Don't create and add the progress view in pressDownload:. Instead, create it when the view is created but set it to hidden. Then when you need it just un-hide it. When you reuse a view be sure to set the appropriate value based on whether you are downloading the item at that index.