UITableView reloading data objective c - ios

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.

Related

UIScrollView swipe with timer in iOS

I have the following code that render scroll view inside table view with three pages, I want the pages to be changed each 5 seconds , how can I do that ?
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier: sliderIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sliderIdentifier];
}
if (sliderItems != nil && sliderItems.count > 0) {
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, 200)];
scroll.scrollEnabled = YES;
for (int i = 0; i < sliderItems.count ; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIImageView *awesomeView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, 200)];
ItemResponse *test = [ItemResponse new];
test = sliderItems[i];
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSString *urlStr = test.listingImage;
NSURL *imageUrl = [NSURL URLWithString:urlStr];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
awesomeView.image = [UIImage imageWithData:imageData];
[scroll addSubview:awesomeView];
UILabel *iconAdLabel = [[UILabel alloc]init];
iconAdLabel.frame = CGRectMake(0 + (i * self.view.frame.size.width),130,self.view.frame.size.width,70);
iconAdLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
NSString *titleStr = [NSString stringWithFormat:#" %# ", test.listingTitle];
iconAdLabel.text = titleStr;
UIColor *color = [self getUIColorObjectFromHexString:#"#000000" alpha:0.6];
iconAdLabel.backgroundColor = color;
UIColor *textcolor = [self getUIColorObjectFromHexString:#"#ffffff" alpha:1.0];
iconAdLabel.textColor = textcolor;
iconAdLabel.textAlignment = NSTextAlignmentRight;
UIFont *font=[UIFont fontWithName:#"NotoKufiArabic" size:14.0f];
iconAdLabel.font = font;
iconAdLabel.numberOfLines = 2;
[scroll addSubview:iconAdLabel];
});
});
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * sliderItems.count , 200);
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:scroll];
});
});
}
return cell;
You can use a NSTimer object
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(timerAction) userInfo:nil repeats:YES];
with action
-(void)timerAction
{
[scroll scrollRectToVisible:CGRectMake(x, y, width, height) animated:YES];
}
Also you need to invalidate the timer Object when the ViewController Disappears. So if you have multiple cells , use an NSArray to keep track of the timer objects and invalidate when no longer needed [timer invalidate]

AVAudioSession crashing in new Thread

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?

Radio Button Issues

I am using onegray's Radio button class in one of my projects. the one mentioned here: Best radio-button implementation for IOS
I am using these radio buttons for my answer choices on a quiz. when the user clicks the next button, the labels are populated with new choices. the only problem is that the old ones dont disappear. So when I click next, the new set of buttons are placed on top of the old ones.
what is the simplest way to first check to see if they already exist.. and if so.. delete them.. before displaying the new ones?
here is my code.
#interface LABViewControllerQuiz ()
#end
#implementation LABViewControllerQuiz
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
int counter =0;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_fileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"quizQuestions" ofType:#"txt"] encoding:NSUTF8StringEncoding error: nil];
_theScanner = [NSScanner scannerWithString:_fileContents];
_separator = [NSCharacterSet characterSetWithCharactersInString:#"~"];
_lineBreak =[NSCharacterSet characterSetWithCharactersInString:#"#"];
_alreadyGeneratedNumbers =[[NSMutableArray alloc]init];
_numQuestions =0;
_userAnswers = [[NSMutableArray alloc]init];
_answerKey = [[NSMutableArray alloc]init];
[self nextQuestion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)nextQuestion:(UIButton *)sender
{
_NextQuestionButton.enabled = YES;
_submitButton.enabled = NO;
NSLog(#"NumQuestion = %d", _numQuestions);
if (_numQuestions >9)
{
_NextQuestionButton.enabled = NO;
_submitButton.enabled = YES;
}else
{
int r = arc4random() %20;
while ([_alreadyGeneratedNumbers containsObject:[NSNumber numberWithInt:r]])
{
r = arc4random() %20;
}
[_alreadyGeneratedNumbers addObject:[NSNumber numberWithInt:r]];
while(![_theScanner isAtEnd])
{
NSLog(#"Location= %d", [_theScanner scanLocation]);
NSLog(#"Already Generated numbers:");
int i =0;
while (i < [_alreadyGeneratedNumbers count])
{
NSLog(#"%#", [_alreadyGeneratedNumbers objectAtIndex:i]);
i++;
}
NSString *line;
_lineArray = [[NSMutableArray alloc] init];
[_theScanner scanUpToCharactersFromSet:_lineBreak intoString:&line];
[_theScanner setCharactersToBeSkipped:_lineBreak];
NSScanner *inner = [NSScanner scannerWithString:line];
NSString *word;
int wordCount = 0;
NSLog(#"r = %d counter = %d", r, counter);
if (counter ==r)
{
while(![inner isAtEnd])
{
[inner scanUpToCharactersFromSet:_separator intoString:&word];
[inner setCharactersToBeSkipped:_separator];
[_lineArray insertObject:word atIndex:wordCount];
_questionText.text = [NSString stringWithFormat:#"Question %d \n %#", _numQuestions +1,[_lineArray objectAtIndex:0]];
wordCount++;
[_theScanner setScanLocation:0];
counter = 0;
}
[sender setHidden:YES];
NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:4];
CGRect btnRect = CGRectMake(25, 420, 300, 30);
for (NSString* optionTitle in #[[_lineArray objectAtIndex:1], [_lineArray objectAtIndex:2], [_lineArray objectAtIndex:3], [_lineArray objectAtIndex:4]])
{
RadioButton* btn = [[RadioButton alloc] initWithFrame:btnRect];
[btn addTarget:self action:#selector(onRadioButtonValueChanged:) forControlEvents:UIControlEventValueChanged];
btnRect.origin.y += 40;
[btn setTitle:optionTitle forState:UIControlStateNormal];
[btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
[self.view addSubview:btn];
[buttons addObject:btn];
}
[buttons[0] setGroupButtons:buttons]; // Setting buttons into the group
[buttons[0] setSelected:NO]; // Making the first button initially selected
NSLog(#"the question is = %#", [_lineArray objectAtIndex:0]);
//NSLog(#"Line arrayINDEX %d = %#", wordCount,[_lineArray objectAtIndex:wordCount]); _numQuestions ++;
break;
}else
{
counter ++;
}
}
}
[_answerKey addObject:[_lineArray objectAtIndex:5]];
}
-(void) onRadioButtonValueChanged:(RadioButton*)sender
{
// Lets handle ValueChanged event only for selected button, and ignore for deselected
if(sender.selected)
{
NSLog(#"Selected: %#", sender.titleLabel.text);
}
}
Save buttons as an instance variable. You're already adding all your buttons into the array, you just throw the array out for some reason.
#interface LABViewControllerQuiz ()
#property (strong) NSMutableArray *buttons;
#end
And then this line:
NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:4];
Becomes these lines:
if (self.buttons) {
[self.buttons makeObjectsPerformSelector:#selector(removeFromSuperview)];
[self.buttons removeAllObjects];
} else {
self.buttons = [NSMutableArray arrayWithCapacity:4];
}

iOS scrollview adaption for landscape

I am using the following scrollview from a tutorial series. It works fine in portrait mode but the frame does not handle the switch to landscape mode. Is there a fast way to fix this? Thanks in advance.
- (void)viewDidLoad
{
[super viewDidLoad];
pageControlBeingUsed = NO;
NSString *plistFile = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", self.displayRegion] ofType:#"plist"];
self.SituationData = [NSArray arrayWithContentsOfFile:plistFile];
self.singleSituation = [SituationData objectAtIndex:selectedIndexPath];
self.SituationScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)]; //distinguishing between iphone 4 and 5 screen
self.SituationScrollView.delegate = self;
self.SituationScrollView.showsHorizontalScrollIndicator = NO;
self.SituationScrollView.pagingEnabled = YES;
self.SituationScrollView.backgroundColor = [UIColor clearColor];
//adding to the view
[self.view addSubview:self.SituationScrollView];
//getting the base indicator
int baseNum = self.selectedIndexPath ;
self.plistFile = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#", self.displayRegion] ofType:#"plist"];
self.auswahl = [NSArray arrayWithContentsOfFile:self.plistFile];
self.SituationScrollView.contentSize = CGSizeMake(self.SituationScrollView.frame.size.width *[self.auswahl count], self.SituationScrollView.frame.size.height);
for (NSInteger i=1; i <= [[self auswahl] count]; i++){
UIImage *situationImage = [UIImage imageNamed:[NSString stringWithFormat:#"main%#", [[self.auswahl objectAtIndex:i - 1] objectForKey:#"nat_num"]]];
UIImageView *situationView = [[UIImageView alloc] initWithImage:situationImage];
UILabel *situationTitle = [[UILabel alloc] init];
situationTitle.text = [NSString stringWithFormat:#"%#", [[self.auswahl objectAtIndex: i - 1] objectForKey:#"species"]];
[situationTitle setTextColor:[UIColor blackColor]];
[situationTitle setBackgroundColor:[UIColor clearColor]];
UITextView *description = [[UITextView alloc] init];
description.text = [NSString stringWithFormat:#"%#", [[self.auswahl objectAtIndex: i - 1] objectForKey:#"description"]];
[description setTextColor:[UIColor blackColor]];
[description setBackgroundColor:[UIColor clearColor]];
[description setUserInteractionEnabled:NO];
situationView.frame = CGRectMake((320 * (i-1)) + SIT_IMG_X, 66, 94, 87);
situationTitle.frame = CGRectMake((320 * (i-1)) + TOP_DATA_X, 250, 240, 14);
description.frame = CGRectMake((320 * (i-1)) + DESC_X, DESC_Y, DETAIL_WIDTH, 100);
[self.SituationScrollView addSubview:situationView];
[self.SituationScrollView addSubview:situationTitle];
[self.SituationScrollView addSubview:description];
}
use a global BOOL variable
BOOl isLandscape =NO;
while writing frames
situationView.frame = CGRectMake(isLandscape?0:0, isLandscape?0:0, isLandscape?320:480 , isLandscape?480:320);
in orientation method write again
if(orientation == Landscape)
{
isLandscape=YES;
}
else
{
isLandscape=NO;
}
situationView.frame = CGRectMake(isLandscape?0:0, isLandscape?0:0, isLandscape?320:480 , isLandscape?480:320);
Check it as a sample it will work depending on it you can use
A little googlefu revealed this SO thread in which Mike states loading the UIScrollView in the viewWillAppear method instead of the viewDidLoad method, then the UIScrollView should appear as desired.

Adding independent Progress VIew for indicate download in iCarousel

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.

Resources