Radio Button Issues - ios

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];
}

Related

How can I set/get tag value (NSInteger) for UISwitch

I have dynamic UISwitches that I create using the for loop. I give the tag value for each control to have an identity. I want to reach these values ​​later, but I get 0 each time. What I'm doing wrong?
for(int i = 0;i < self.extraArray.count; i++) {
ProductPropertiesModel *model = (ProductPropertiesModel *)[self.extraArray objectAtIndex:i];
UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectZero];
switchButton.translatesAutoresizingMaskIntoConstraints = false;
switchButton.tag = [model Id];
[switchButton setOn:NO];
[self.view addSubview:switchButton];
[switchButton addTarget:self action:#selector(setState:)
forControlEvents:UIControlEventValueChanged];
}
-(void)setState:(id)sender
{
UISwitch *uiswitch = (UISwitch *)sender;
NSInteger tagInteger= uiswitch.tag;
NSLog(#"%#", [NSString stringWithFormat:#"%li",(long)tagInteger]);
}
The tag value is 0, but that is wrong.
I found the problem. I just made a typo. I noticed that I was writing a typo when I was taking json data. I noticed Id writing instead of id.
NSError *jsonError;
self.extraJsonArray = nil;
self.extraJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
self.extraArray = [[NSMutableArray alloc]init];
for(int j = 0;j < self.extraJsonArray.count;j++){
#try {
//NSInteger *Id = (NSInteger *)[(NSNumber *)[[self.extraJsonArray objectAtIndex:j]objectForKey:#"Id"] integerValue]; Problem is here
NSInteger *Id = (NSInteger *)[(NSNumber *)[[self.extraJsonArray objectAtIndex:j]objectForKey:#"id"] integerValue];
double price = (double)[(NSNumber *)[[self.extraJsonArray objectAtIndex:j] objectForKey:#"price"] doubleValue];
NSString *property =(NSString *)[[self.extraJsonArray objectAtIndex:j] objectForKey:#"property"];
ProductPropertiesModel *model = [[ProductPropertiesModel alloc] init];
[model setId:Id];
[model setProperty:property];
[model setPrice:price];
[model setChecked:#"No"];
[self.extraArray addObject:model];
} #catch (NSException *exception) {
NSLog(#"%#", exception.reason);
} #finally {
}
}
I would recommend instead setting [model id] as tag, you should set array index as tag.
and then later on in the switch control method, you can get the value from array index, using the code.
ProductPropertiesModel *model = (ProductPropertiesModel *)[self.extraArray objectAtIndex:i];
Hope this helps.
Try this:
for (int i =0; i < self.extraArray.count; i++) {
CGRect frame = CGRectMake(x, y, height, width);
UISwitch *switchControl = [[UISwitch alloc] initWithFrame:frame];
//add tag as index
switchControl.tag = i;
[switchControl addTarget:self action:#selector(setState:) forControlEvents: UIControlEventValueChanged];
[switchControl setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:switchControl];
y= y+50.0;
}
- (IBAction) setState: (UISwitch *) sender {
NSLog(#"no.%d %#",sender.tag, sender.on ? #"On" : #"Off");
//use sender.tag , you know which switch you selected
}

Trouble implementing JBChartView

I'm starting to get brave and am attempting to populate a JBChartView (specifically a line chart) into my application for statistics tracking. I've never worked with a graphing library before but I did my best to look into them and this one seemed very robust. Problem is I'm having trouble getting the plots to work correctly from test data.
When I run the code as follows below, I get [__NSCFConstantString objectAtIndex:] unrecognized selector sent to instance. The offending line is at verticalValueforHorizontalIndex but I can't figure out another way to produce any data. Does anyone have any experience with this or can anyone help me figure out why I'm getting so much trouble here?
Implementation File
#import "waterStatsViewController.h"
#import "JBLineChartView.h"
#import "JBChartView.h"
#import "JBBarChartView.h"
#import "JBChartHeaderView.h"
#import "JBLineChartFooterView.h"
typedef NS_ENUM(NSInteger, JBLineChartLine){
JBLineChartLineSolid,
JBLineChartLineDashed,
JBLineChartLineCount
};
#interface waterStatsViewController ()
- (void)initData;
#end
#implementation waterStatsViewController
- (id)init
{
self = [super init];
if (self)
{
[self initData];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self initData];
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
[self initData];
}
return self;
}
- (void) initData
{
// DEFINE ARRAYS
testArray1 = [[NSArray alloc] initWithObjects:#"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", nil];
testArray2 = [[NSArray alloc] initWithObjects:#"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", nil];
// CREATE MUTABLE ARRAY FOR LINES IN CHART
NSMutableArray *mutableLineCharts = [NSMutableArray array];
// AS LONG AS LINEINDEX IS LESS THEN THE LINE COUNT, INCREASE THE LINE COUNT AND EXECUTE CODE
for (int lineIndex = 0; lineIndex<JBLineChartLineCount; lineIndex++)
{
// CREATE MUTABLE ARRAY FOR DATA IN CHART
NSMutableArray *mutableChartData = [NSMutableArray array];
// AS LONG AS INT I IS LESS THEN THE COUNT OF OBJECTS IN TEST ARRAY 2; INCREASE COUNT AND EXECUTE CODE
for (int i = 0; i < testArray2.count; i++)
{
// ADD OBJECTS FROM TEST ARRAY 2 TO CHART DATA
[mutableChartData addObjectsFromArray:testArray2];
}
// TAKE OBJECTS FROM MUTABLE CHART DATA AND ADD THEM TO OHHHHHH FOR EACH ITEM YOU ADD ANOTHER LINE
[mutableLineCharts addObjectsFromArray:mutableChartData];
}
}
- (void)viewDidLoad
{
self.title = #"Water Quality";
_chartView = [[JBLineChartView alloc] init];
_chartView.delegate = self;
_chartView.dataSource = self;
_chartView.state = 0;
_chartView.backgroundColor = [UIColor blackColor];
_chartView.showsLineSelection = YES;
_chartView.showsVerticalSelection = YES;
_headerView = [[JBChartHeaderView alloc] initWithFrame:CGRectMake(0, 64, 320, 30)];
_chartView.frame = CGRectMake(0, 94, 320, 300);
_footerView = [[JBLineChartFooterView alloc] initWithFrame:CGRectMake(0, 404, 320, 30)];
_headerView.titleLabel.text = #"Alkalinity";
_headerView.titleLabel.textColor = [UIColor whiteColor];
_footerView.leftLabel.text = [testArray1 firstObject];
_footerView.rightLabel.text = [testArray1 lastObject];
_footerView.leftLabel.textColor = [UIColor whiteColor];
_footerView.rightLabel.textColor = [UIColor whiteColor];
_footerView.backgroundColor = [UIColor blackColor];
_footerView.sectionCount = [testArray1 count];
// THIS IS THE VIEW WHEN THE USER INTERACTS WITH THE CHART
/*
_informationView = [[JBChartInformationView alloc] initWithFrame:CGRectMake(0, 0, 40, 300)];
[_informationView setBackgroundColor:[UIColor grayColor]];*/
[_chartView setMinimumValue:1.0f];
[_chartView setMaximumValue:20.0f];
[self.view addSubview:_footerView];
[self.view addSubview:_headerView];
[self.view addSubview:_chartView];
// [self.view addSubview:_informationView];
[_chartView reloadData];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (BOOL)lineChartView:(JBLineChartView *)lineChartView showsDotsForLineAtLineIndex:(NSUInteger)lineIndex;
{
return YES;
}
- (NSUInteger)numberOfLinesInLineChartView:(JBLineChartView *)lineChartView;
{
return 1;
}
- (NSUInteger)lineChartView:(JBLineChartView *)lineChartView numberOfVerticalValuesAtLineIndex:(NSUInteger)lineIndex;
{
return 1;
}
- (CGFloat)lineChartView:(JBLineChartView *)lineChartView verticalValueForHorizontalIndex:(NSUInteger)horizontalIndex atLineIndex:(NSUInteger)lineIndex;
{
return [[[testArray2 objectAtIndex:lineIndex] objectAtIndex:horizontalIndex] floatValue];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
A few issues:
Don't store numeric values as strings in your test arrays.
Remove the mutableLineCharts code; this is leftover from the demo and not needed for your purposes.
I assume you want two lines? One dashed and one solid? If so, return JBLineChartLineCount instead of 1 for numberOfLinesInLineChartView.
Return the numeric value for testArray1 or testArray2 in verticalValueForHorizontalIndex.
Initializing Data
- (void) initData
{
testArray1 = #[#(1), #(2), #(3), #(4), #(5), #(6), #(7), #(8), #(9), #(10)];
testArray2 = #[#(11), #(12), #(13), #(14), #(15), #(16), #(17), #(18), #(19), #(20)];
}
Line Count
- (NSUInteger)numberOfLinesInLineChartView:(JBLineChartView *)lineChartView;
{
return JBLineChartLineCount;
}
Data Count
- (NSUInteger)lineChartView:(JBLineChartView *)lineChartView numberOfVerticalValuesAtLineIndex:(NSUInteger)lineIndex;
{
if (lineIndex == JBLineChartLineSolid)
{
return [self.testArray1 count];
}
else
{
return [self.testArray2 count];
}
return 0;
}
Data Value
- (CGFloat)lineChartView:(JBLineChartView *)lineChartView verticalValueForHorizontalIndex:(NSUInteger)horizontalIndex atLineIndex:(NSUInteger)lineIndex;
{
if (lineIndex == JBLineChartLineSolid)
{
NSNumber *value = (NSNumber *)[self.testArray1 objectAtIndex:horizontalIndex];
return [value floatValue];
}
else
{
NSNumber *value = (NSNumber *)[self.testArray2 objectAtIndex:horizontalIndex];
return [value floatValue];
}
return 0;
}
Hope this helps.

Content not loading on horizontal scroll view

Hi I am building an app in which I want my contents to be displayed on a view which is horizontally scroll-able.
I have implemented the following code for it:
-(void)DownLoadData:(NSString *)indexSelect
{
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)DownloadNext:(NSString *)indexSelect
{
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
}
}
[self loadScrollView];
}
-(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:#""])
{
_imageView1.hidden=YES;
_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,310.0f,159.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._Writer setText:[Dic valueForKey:#"AUTHOR"]];
[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=#"";
}
[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];
[self loadScrollView];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[self DownLoadData:resultDic];
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(loadScrollView)];
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(loadScrollView)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
[self loadScrollView];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
[self loadScrollView];
}
-(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;
}
}
-(void)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]];
}
}
-(void)loadScrollView
{
_scrollView.contentSize = CGSizeMake(0, _scrollView.frame.size.height);
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [_arrUrlLinks count]; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
count=1;
// a page is the width of the scroll view
_scrollView.pagingEnabled = YES;
_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * [_arrUrlLinks count], _scrollView.frame.size.height);
_scrollView.showsHorizontalScrollIndicator =YES;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
pageControl.numberOfPages = [_arrUrlLinks count];
pageControl.currentPage = 0;
[_scrollView addSubview:_txtView];
[_txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
[controller.view addSubview:_txtView];
// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count])
return;
// replace the placeholder if necessary
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"])
{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
}
else{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController_ipad" bundle:nil];
}
[controller initWithPageNumber:page];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"loadscrollviewwithpage");
[viewControllers replaceObjectAtIndex:page withObject:controller];
// [controller release];
}
// add the controller's view to the scroll view
if (nil == controller.view.superview) {
CGRect frame = _scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
// _txtView.frame=frame;
// _imageview.frame=frame;
// _txtView.frame=CGRectMake(4.0f,316.0f,310.0f,159.0f );
_txtView=#"hello";
// [controller.view addSubview:_txtView];
[_imageView1 addSubview:controller.view];
// [_txtView addSubview:controller.view];
// [scrollView addSubview:controller.view];
NSLog(#"loadscrollviewwithpage................>>>>>>>>>>>>");
// [self._header setText: [Dic valueForKey:#"header"]];
// [self DownLoadData:resultDic];
//[self SetValuesInUserInterface:Dic];
[self DownloadNext:resultDic];
}
}
- (void)unloadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count]) return;
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller != [NSNull null]) {
if (nil != controller.view.superview)
[controller.view removeFromSuperview];
[viewControllers replaceObjectAtIndex:page withObject:[NSNull null]];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"Unloadscrollviewwithpage");
// [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// NSLog(#"current page %d",page);
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self unloadScrollViewWithPage:page - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self unloadScrollViewWithPage:page + 2];
count=page+1;
// [self newCountTitleSet];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollViewLoc
{
CGFloat pageWidth = scrollViewLoc.frame.size.width;
CGPoint translation = [scrollViewLoc.panGestureRecognizer translationInView:scrollViewLoc.superview];
int page = floor((scrollViewLoc.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if(translation.x > 0)
{
if(_strCurrentNewsSelect!=0)
{
if(page==0)
{
NSLog(#"OK");
NSLog(#"scrollviewwillbegindragging=0");
[self DownLoadDataPrevious:[_strCurrentNewsSelect.integervalue]-1];
}
}
else{
if(page==1)
{
NSLog(#"previous button");
[self btnPreviousClick];
}
}
} else
{
// [_txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_txtView];
// [controller.view addSubview:_imageview];
NSLog(#"loadscrollviewwithpage else");
[self btnPreviousClick];
NSLog(#"previous news");
// if(galleryItemClick+1!=[arrGallaeryUrl count])
//
// {
//
if(page+1==[_arrUrlLinks count])
//
{
//
NSLog(#"====....>>>>>>>");
}
count=count+1;
}
}
By using this code I am able to create the view controllers according to my array count[_arrUrlLinks] but the contents are not loaded on these views. On my first view I can only see an image view in black color rest of the views are blank.
How can I get the contents loaded on these views?

Play audio from Parse via UIButton

I've been working on an app that allows audio to be played from Parse (like a social network), but am having trouble getting the code to not have errors.
My .h file
#import <UIKit/UIKit.h>
#interface TalklineViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIScrollView *wallScroll;
#end
My .m file
#interface TalklineViewController ()
#property (nonatomic, retain) NSArray *wallAudioArray;
#end
#implementation TalklineViewController
#synthesize wallAudioArray = _wallAudioArray;
#synthesize wallScroll = _wallScroll;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)getWallAudio
{
//Prepare the query to get all the images in descending order
//1
PFQuery *query = [PFQuery queryWithClassName:#"AudioObject"];
//2
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//3
if (!error) {
//Everything was correct, put the new objects and load the wall
self.wallAudioArray = nil;
self.wallAudioArray = [[NSArray alloc] initWithArray:objects];
[self loadWallViews];
} else {
//4
NSString *errorString = [[error userInfo] objectForKey:#"error"];
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlertView show];
}
}];
}
-(void)loadWallViews
{
//Clean the scroll view
for (id viewToRemove in [self.wallScroll subviews]){
if ([viewToRemove isMemberOfClass:[UIView class]])
[viewToRemove removeFromSuperview];
}
//For every wall element, put a view in the scroll
int originY = 10;
for (PFObject *audioObject in self.wallAudioArray){
//1
//Build the view with the image and the comments
UIView *wallAudioView = [[UIView alloc] initWithFrame:CGRectMake(10, originY, self.view.frame.size.width - 20 , 300)];
//2
//Add the image
PFFile *audio = (PFFile *)[audioObject objectForKey:#"audio"];
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
userAudio.frame = CGRectMake(0, 0, wallAudioView.frame.size.width, 200);
[wallAudioView addSubview:userAudio];
//3
//Add the info label (User and creation date)
NSDate *creationDate = audioObject.createdAt;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm dd/MM yyyy"];
//4
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 210, wallAudioView.frame.size.width,15)];
infoLabel.text = [NSString stringWithFormat:#"Uploaded by: %#, %#", [audioObject objectForKey:#"user"], [df stringFromDate:creationDate]];
infoLabel.font = [UIFont fontWithName:#"Arial-ItalicMT" size:9];
infoLabel.textColor = [UIColor whiteColor];
infoLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:infoLabel];
//5
//Add the comment
UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 240, wallAudioView.frame.size.width, 15)];
commentLabel.text = [audioObject objectForKey:#"comment"];
commentLabel.font = [UIFont fontWithName:#"ArialMT" size:13];
commentLabel.textColor = [UIColor whiteColor];
commentLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:commentLabel];
//6
[self.wallScroll addSubview:wallAudioView];
originY = originY + wallAudioView.frame.size.width + 20;
}
//7
//Set the bounds of the scroll
self.wallScroll.contentSize = CGSizeMake(self.wallScroll.frame.size.width, originY);
}
/*
#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.
}
*/
#end
The problem line is:
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
Any help is greatly appreciated!
UIButton doesn't have an audioWithData method, so that's the biggest issue here; instead, add a target to the button to play the audio with a seperate method:
UIButton *userAudio = [UIButton buttonWithType:UIButtonTypeSystem];
[userAudio setFrame:CGRectMake(20, 20, 100, 44)];
[userAudio setTitle:#"Play Audio!" forState:UIControlStateNormal];
[userAudio addTarget:self action:#selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:userAudio];
- (void)playAudio
{
// Your audio data and playing code here
// audio.getData
}

UITableView reloading data objective c

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.

Resources