I have a Method wich create an UIScrollView and your subviews programmatically. One of your views is a MoviewPlayer...While the scrollview is being created, I need to allow the user to exit the screen (before the loading ends). Then, I've called this method in another NSThread.
But I'm getting the following error:
[__NSCFData _pickableRoutesDidChangeNotification:]: unrecognized selector sent to instance
I think it's not possible to do it in another Thread. Then, How could I allow the user to exit the view before the loading ends?
Theres my code:
-(void) viewDidAppear:(BOOL)animated {
[NSThread detachNewThreadSelector:#selector(criarScrollMidias:) toTarget:self withObject:self.eventoAtual];
}
-(void) criarScrollMidias:(Evento *)evento {
NSLog(#"criar scroll midias");
NSMutableArray *listaImagens = evento.atracao.images;
NSMutableArray *listaVideos = evento.atracao.videos;
if([listaVideos count] > 0) {
self.listaVideoPlayers = [[NSMutableArray alloc]init];
}
[self.scrollImVd setPagingEnabled:YES];
if(![self.eventoAtual.atracao.imageLarge isKindOfClass:[NSNull class]])
{
UIImageView *imgViewAtracao = [[UIImageView alloc]initWithImage:self.eventoAtual.atracao.imageLarge];
[imgViewAtracao setContentMode:UIViewContentModeScaleAspectFit];
[imgViewAtracao setFrame:CGRectMake(0, 0, self.scrollImVd.frame.size.width, self.scrollImVd.frame.size.height)];
[self.scrollImVd addSubview:imgViewAtracao];
}
for (int iCnt = 0; iCnt < [listaImagens count]; iCnt++) {
NSString *imgURL = [listaImagens objectAtIndex:iCnt];
UIImage *imagemAtracao = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]]];
UIImageView *imgViewAtracao = [[UIImageView alloc]initWithImage:imagemAtracao];
[imgViewAtracao setContentMode:UIViewContentModeScaleAspectFit];
if(![self.eventoAtual.atracao.imageLarge isKindOfClass:[NSNull class]])
[imgViewAtracao setFrame:CGRectMake(0+self.scrollImVd.frame.size.width*(iCnt+1), 0, self.scrollImVd.frame.size.width, self.scrollImVd.frame.size.height)];
else
[imgViewAtracao setFrame:CGRectMake(0+self.scrollImVd.frame.size.width*iCnt, 0, self.scrollImVd.frame.size.width, self.scrollImVd.frame.size.height)];
[self.scrollImVd addSubview:imgViewAtracao];
}
for (int iCnt = 0; iCnt < [listaVideos count]; iCnt++) {
NSString *videoURLStr = [listaVideos objectAtIndex:iCnt];
NSURL *videoURL = [NSURL URLWithString:videoURLStr];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
[moviePlayer setShouldAutoplay:NO];
[moviePlayer.view setBackgroundColor:[UIColor colorWithPatternImage:[self gerarPreviewVideo:videoURL]]];
CGFloat posicaoInicial = 0.0;
if(![self.eventoAtual.atracao.imageLarge isKindOfClass:[NSNull class]])
posicaoInicial = self.scrollImVd.frame.size.width * ([listaImagens count] + 1);
else
posicaoInicial = self.scrollImVd.frame.size.width * [listaImagens count];
[moviePlayer.view setFrame:CGRectMake(posicaoInicial+self.scrollImVd.frame.size.width*iCnt, 0, self.scrollImVd.frame.size.width, self.scrollImVd.frame.size.height)];
UIButton *playButton = [[UIButton alloc] initWithFrame:CGRectMake(moviePlayer.view.frame.origin.x+(self.scrollImVd.frame.size.width/2)-34, moviePlayer.view.frame.origin.y+(self.scrollImVd.frame.size.height/2)-33, 67, 66)];
[playButton setImage:[UIImage imageNamed:#"play.png"] forState:UIControlStateNormal];
playButton.tag = iCnt;
[playButton addTarget:self action:#selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollImVd addSubview:moviePlayer.view];
[self.scrollImVd addSubview:playButton];
[self.listaVideoPlayers addObject:moviePlayer];
}
if(![self.eventoAtual.atracao.imageLarge isKindOfClass:[NSNull class]])
[self.scrollImVd setContentSize:CGSizeMake(self.scrollImVd.frame.size.width * ([listaImagens count] + [listaVideos count] + 1), self.scrollImVd.frame.size.height)];
else
[self.scrollImVd setContentSize:CGSizeMake(self.scrollImVd.frame.size.width * ([listaImagens count] + [listaVideos count]), self.scrollImVd.frame.size.height)];
[self.viewLoading setHidden:YES];
}
I've debugged and discovered that the problem is when I try to generate the preview in another Thread:
-(UIImage *) gerarPreviewVideo:(NSURL *)videoURL {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *error = NULL;
CMTime time = CMTimeMake(1, 65);
CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&error];
UIImage *thumbnail= [[UIImage alloc] initWithCGImage:refImg];
return thumbnail;
}
How could I resolve it?
Related
1) In my application, I want to zoom and pinch an image. In xib file, there is a imageView inside a scrollview.Page control is used for swiping images. For a single image it gets zoomed, but for multiple images(coming from web service) it is not getting swipe and zoom.
In setMultipleImages method, images are not getting zoomed and swiped, while if image is single it gets zoom properly.
2) In UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]]; line code, want to replace uiimage with uiimageview. How can I do it?
My code is:
-(void)setMultipleImages{
for (int i = 0; i < [imageMArray count]; i++){
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:i] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if (![[AppDelegateHelper getInstance] fileExist:logoName])
{
NSString *imageURL = [[NSString alloc]initWithFormat:#"%#%#",[UrlBuilder getWebsiteUrl],[imageMArray objectAtIndex:i]];
[self startProcessing];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
[activityIndicator stopAnimating];
DebugLog(#"%f,%f",image.size.width,image.size.height);
NSArray *docDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [docDir objectAtIndex:0];
DebugLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",cacheDirectory,[imageNameArray lastObject]];
NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data1 writeToFile:pngFilePath atomically:YES];
}
}
[self loadImageData];
}
-(void)loadImageData
{
int X =0;
for (int s=0; s<imageMArray.count; s++) {
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:s] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if([[AppDelegateHelper getInstance] loadImage:logoName] != nil)
{
// UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[[AppDelegateHelper getInstance] loadImage:logoName]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
else
{
//UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[UIImage imageNamed:#"NoImage.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
}
self.pageControl.numberOfPages = [imageMArray count];
scrollView.contentSize = CGSizeMake(X,scrollView.frame.size.height);
lblCount.text = [[NSString alloc]initWithFormat:#"1 sur %lu",(unsigned long)imageMArray.count];
}
Add all your images to imageview. Then apply pinchguesture to images view for zoom effect.
Pinch Guesture:
UIPinchGestureRecognizer *imageviewguesture=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:#selector(ImageViewPinchGuesture:)];
add pinch guesture to your image view:
[YourImageView addGestureRecognizer:imageviewguesture];
Make your selector method:
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer{
pinGuestureregonizer.view.transform = CGAffineTransformScale(pinGuestureregonizer.view.transform, pinGuestureregonizer.scale, pinGuestureregonizer.scale);
pinGuestureregonizer.scale = 1;
}
In your .h file add this line
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer;
To check effect in simulator Press Cmd+alt then press left mouse pad button and drag.
Hope this will Help. Don't forget to accept the answer if it helps you.
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];
}
Just updated to iOS 8.0 this morning. I have a piece of code which created some labels and displays them on the scree next to some images. It was working fine before the update. Now the label and the image is not displaying. Can some one please help as I have tried everything I can think of and nothing has solved my issue and couldn't find anyone else with a similar issue. Code attached below.
UIView *labelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, kCategoryLabelHieght)];
labelView.backgroundColor = [self colorWithHexString:#"2D2D2D"];
UILabel *categoryTitle = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 200, kCategoryLabelHieght)];
categoryTitle.textAlignment = NSTextAlignmentLeft;
categoryTitle.text = text;
categoryTitle.font = [UIFont fontWithName:#"HelveticaNeue" size:14];
codeAppDelegate *appDelegate = (codeAppDelegate *)[[UIApplication sharedApplication] delegate];
NSArray *fetchedCategory = [appDelegate getCategoryByName:text];
UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(10, 2, 20, 20)];
if(fetchedCategory.count)
{
for (int t=0; t<fetchedCategory.count; t++) {
Dealcategory_List *catList = [fetchedCategory objectAtIndex:t];
NSString *titleImage = [self URLEncodeString:[NSString stringWithFormat:#"%#",catList.image]];
NSURL *url = [NSURL URLWithString:titleImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgTabs = [UIImage imageWithData:data];
// [header2 setImage:imgTabs forState:UIControlStateNormal];
[imgTabs resizableImageWithCapInsets: UIEdgeInsetsMake(5, 10, 2, 0) resizingMode: UIImageResizingModeTile];
img.image= imgTabs;
}
}
else
{
NSArray *fetchedNewsCategory = [appDelegate getNewsCategoryByName:text];
if(fetchedNewsCategory.count > 0)
{
for (int t=0; t<fetchedNewsCategory.count; t++) {
News_Categories *catList = [fetchedNewsCategory objectAtIndex:t];
NSString *titleImage = [self URLEncodeString:[NSString stringWithFormat:#"%#",catList.category_image]];
NSURL *url = [NSURL URLWithString:titleImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgTabs = [UIImage imageWithData:data];
// [header2 setImage:imgTabs forState:UIControlStateNormal];
[imgTabs resizableImageWithCapInsets: UIEdgeInsetsMake(10, 10, 2, 0) resizingMode: UIImageResizingModeTile];
img.image= imgTabs;
}
}
else
{
NSArray *fetchedCompetition = [appDelegate getCompetitionByName:text];
if(fetchedCompetition.count > 0)
{
for (int t=0; t<fetchedCompetition.count; t++) {
Competitions_List *catList = [fetchedCompetition objectAtIndex:t];
NSString *titleImage = [self URLEncodeString:[NSString stringWithFormat:#"%#",catList.competition_tab_image]];
NSURL *url = [NSURL URLWithString:titleImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgTabs = [UIImage imageWithData:data];
// [header2 setImage:imgTabs forState:UIControlStateNormal];
[imgTabs resizableImageWithCapInsets: UIEdgeInsetsMake(10, 10, 2, 0) resizingMode: UIImageResizingModeTile];
img.image= imgTabs;
break;
}
}
}
}
categoryTitle.textColor = color;
[labelView addSubview:img];
[labelView addSubview:categoryTitle];
[self.contentView addSubview:labelView];
UIView *labelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, kCategoryLabelHieght)];
You are defining a UIView but allocating a UILabel. iOS 8 is less tolerant to errors like this. Try to change it to
UIView *labelView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, kCategoryLabelHieght)];
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.