In my quiz I have several answers. Correct answers are in plist.
here it is
<array>
<dict>
<key>QuestionTitle</key>
<string>Веки являются</string>
<key>Answers</key>
<array>
<string>частью глазного яблока</string>
<string>защитным аппаратом органа зрения</string>
<string>и тем, и другим</string>
<string>ни тем, ни другим</string>
</array>
<key>CorrectAnswer</key>
<array>
<integer>0</integer>
<integer>1</integer>
</array>
</dict>
Now I can't guess how to make check for answers that User answered
I may create variables 0,1,2,3 for A,B,C,D answers but how I should compare it with CorrectAnswer Array
There is my m. file code
NSString* path = [[NSBundle mainBundle] pathForResource:#"Questions2" ofType:#"plist"];
NSMutableArray *questionsDict = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSUInteger count = [questionsDict count];
for (NSUInteger i = 0; i < count; ++i)
{
int nElements = count - i;
int n = (arc4random()% nElements) + i;
[questionsDict exchangeObjectAtIndex:i withObjectAtIndex:n];
}
self.questions = [questionsDict copy];
currentQuestion = 0;
NSDictionary* nextQuestion =
[self.questions objectAtIndex: currentQuestion];//[self.questions objectForKey:
[NSString stringWithFormat:#"%d", currentQuestion]];
NSMutableArray *array = [nextQuestion[#"Answers"] mutableCopy];
self.labelA.text = [array objectAtIndex:0];
self.labelB.text = [array objectAtIndex:1];
self.labelC.text = [array objectAtIndex:2];
self.labelD.text = [array objectAtIndex:3];
self.labelQuestion.text = [nextQuestion objectForKey:#"QuestionTitle"];
//Button D (A,B,C the same)
- (IBAction)fourButton:(id)sender
{
if (chekColorD == 0)
{
chekColorD++;
[buttonD setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
//self.stringD = #"D";
}
else
{
chekColorD = 0;
[buttonD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
// self.stringD = nil;
}
}
//NExt question button
- (IBAction)nextQuestion:(id)sender
{
// Тут делаешь сравнение правильных ответов
chekColorA = 0; chekColorB = 0; chekColorC = 0; chekColorD = 0;
[buttonA setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttonB setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttonC setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttonD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
if ([self.highScore integerForKey:#"HighScore"]<numCorrect){
[self.highScore setInteger:numCorrect forKey:#"HighScore"];
[self.highScore synchronize];
}
currentQuestion++;
if (currentQuestion <= [self.questions count]){
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
self.labelHighestScore.text = [NSString stringWithFormat:#"%d",
[self.highScore integerForKey:#"HighScore"]];
NSDictionary* nextQuestion = [self.questions objectAtIndex: currentQuestion];
NSMutableArray *array = [nextQuestion[#"Answers"] mutableCopy];
self.labelA.text = [array objectAtIndex:0];
self.labelB.text = [array objectAtIndex:1];
self.labelC.text = [array objectAtIndex:2];
self.labelD.text = [array objectAtIndex:3];
self.labelQuestion.text = [nextQuestion objectForKey:#"QuestionTitle"];
//NSLog(#"%d количество вопросов", countQuestion);
}
else{
currentQuestion --;
}
}
You can compare two string like this:
if ([#"string1" isEqualToString:#"string2"]) {
// YES it s the same
}
else{
// no it s not the same
}
for example [labelA.text isEqualToString:correctAnswerString]. I recomend you to make buttons for answers: button1: firstAnswer, button2: secondAnswer and so on. When user tap on it, you can catch the sender which will be a UIButton, and if you set the button's title for the answer, you can compare the (UIButton*)sender.titleLabel.text isEqualToString:correctAnswer
// the question is: Lion is a...
UIButton* button1 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
UIButton* button2 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
UIButton* button3 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
UIButton* button4 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
[button1 setTitle:#"animal" forState:UIControlStateNormal];
[button2 setTitle:#"car" forState:UIControlStateNormal];
[button3 setTitle:#"tv" forState:UIControlStateNormal];
[button4 setTitle:#"radio station" forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button2 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button3 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button4 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
-(bool) checkAnswer:(id)sender{
NSString* correctString = #"animal";
UIButton* tappedButton = (UIButton*)sender;
if ([tappedButton.titleLabel.text isEqualToString:correctString]) {
return YES;
}
return NO;
}
Related
I am developing IOS App. I Create TextField and Button Dynamically and Set tag value.but problem is that when click button to get textfield first index value that show null. only last index value of textfield i am get not for other What is the problem. Thanks in Advance.
Code..
- (void)addfields{
_field = [[UITextField alloc]initWithFrame:CGRectMake(5.0f, 5.0f, 195.0f, 30.0f)];
_field.layer.borderColor=[[UIColor colorWithRed:211.0f/255.0f
green:211.0f/255.0f
blue:211.0f/255.0f
alpha:1.0] CGColor];
[_field.layer setBorderWidth: 1.0];
//_field.tag = count;
[_filterPossibleValueView addSubview:_field];
_addField = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, 5.0f, 30.0f, 30.0f)];
_addField.backgroundColor = [UIColor blackColor];
//_addField.tag = count;
[_addField addTarget:self action:#selector(customFieldAdd:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:_addField];
}
- (IBAction)customFieldAdd:(id)sender{
[_addfieldArray addObject:_field];
[_scroller setScrollEnabled:YES];
_scroller.contentSize=CGSizeMake(240.0f, _field.frame.size.height+x+50);
[_copyfield removeFromSuperview];
[copyAddButton removeFromSuperview];
x = 10;
y = 10;
for( int i = 0; i < [_addfieldArray count]; i++ ) {
_copyfield = [[UITextField alloc]initWithFrame:CGRectMake(5.0, x + _field.frame.size.height, 195.0f, 30.0f)];
_copyfield.layer.borderColor=[[UIColor colorWithRed:211.0f/255.0f
green:211.0f/255.0f
blue:211.0f/255.0f
alpha:1.0] CGColor];
_copyfield.tag = i;
[_copyfield.layer setBorderWidth: 1.0];
[_filterPossibleValueView addSubview:_copyfield];
x = x+_field.frame.size.height+10;
copyAddButton = [[UIButton alloc]initWithFrame:CGRectMake(202.0f, y + _addField.frame.size.height, 30.0f, 30.0f)];
copyAddButton.backgroundColor = [UIColor blueColor];
copyAddButton.tag = i;
[copyAddButton addTarget:self action:#selector(customFieldDelete:) forControlEvents:UIControlEventTouchUpInside];
[_filterPossibleValueView addSubview:copyAddButton];
y = y+_addField.frame.size.height+10;
count++;
}
}
- (IBAction)customFieldDelete:(id)sender{
UIButton *button = (UIButton*)sender;
NSInteger index = button.tag;
[_addfieldArray removeObjectAtIndex:index];
// UITextField *text = (UITextField *)[_copyfield viewWithTag:index];
// NSLog(#"%ld",(long)text.tag);
UITextField *txtField = [_filterPossibleValueView viewWithTag:index];
NSLog(#"%#",txtField.text);
// [_copyfield removeFromSuperview];
// [copyAddButton removeFromSuperview];
}
I have created an sample app for dynamic fields. And getting the textfield's value on Button click. This example code will solve out your problem.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
NSMutableArray *formArr;
NSMutableArray *txtfldArr;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
formArr = [[NSMutableArray alloc] init];
txtfldArr = [[NSMutableArray alloc] init];
UITextField *txtfld = [[UITextField alloc] init];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:#"string" forKey:#"labelName"];
[dict1 setObject:#"name" forKey:#"labelFor"];
[dict1 setObject:#"1" forKey:#"tag"];
[dict1 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict1];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
[dict2 setObject:#"string" forKey:#"labelName"];
[dict2 setObject:#"email" forKey:#"labelFor"];
[dict2 setObject:#"2" forKey:#"tag"];
[dict2 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict2];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
[dict3 setObject:#"string" forKey:#"labelName"];
[dict3 setObject:#"phone" forKey:#"labelFor"];
[dict3 setObject:#"3" forKey:#"tag"];
[dict3 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict3];
NSMutableDictionary *dict4 = [[NSMutableDictionary alloc] init];
[dict4 setObject:#"string" forKey:#"labelName"];
[dict4 setObject:#"address" forKey:#"labelFor"];
[dict4 setObject:#"4" forKey:#"tag"];
[dict4 setObject:txtfld forKey:#"txtFld"];
[formArr addObject:dict4];
int y = 70;
for (int i = 0; i < [formArr count]; i++) {
NSString *txtfldName = [NSString stringWithFormat:#"%#",[[formArr objectAtIndex:i] objectForKey:#"labelFor"]];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(30, y+4, 80, 25)];
lbl.text = txtfldName;
lbl.textColor = [UIColor darkGrayColor];
[self.view addSubview:lbl];
UITextField *lbl_txtfld = [[UITextField alloc] initWithFrame:CGRectMake(120, y, 150, 30)];
lbl_txtfld.text = #"";
lbl_txtfld.delegate = self;
lbl_txtfld.textColor = [UIColor whiteColor];
lbl_txtfld.backgroundColor = [UIColor blackColor];
[self.view addSubview:lbl_txtfld];
[[formArr objectAtIndex:i] setObject:lbl_txtfld forKey:#"txtFld"];
y += 40;
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonClicked:(id)sender {
for (int i = 0; i < [formArr count]; i++) {
NSString *labelName = [NSString stringWithFormat:#"%#",[[formArr
objectAtIndex:i] objectForKey:#"labelFor"]];
UITextField *txtfld = [[formArr objectAtIndex:i]
objectForKey:#"txtFld"];
NSLog(#"txtfld value for %# = %#",labelName,txtfld.text);
}
}
For each of my buttons I am doing the same methods but using a different variable from my array, this does work fine but its a lot of code and I will have around 40 buttons by the end. I was wondering if I could use the button tag to match with the objectAtIndex in my array, so I will not need to re-write for each tag, Hope this question makes sense, below is my code so far:
- (IBAction)pressCountBtn:(id)sender
{
UIButton * btn = (UIButton *)sender;
int btag = btn.tag;
if(btag == 1)
{
self.presscount1 ++;
[self.pressCountArray replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:self.presscount1]];
if (self.presscount1 > 3)
{
self.presscount1 = 0;
[btn setTitle:[NSString stringWithFormat:#""] forState:UIControlStateNormal];
}
else
[btn setTitle:[NSString stringWithFormat:#"%i",self.presscount1] forState:UIControlStateNormal];
}
else if (btag == 2)
{
self.presscount2 ++;
[self.pressCountArray replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:self.presscount2]];
if (self.presscount2 > 3)
{
self.presscount2 = 0;
[btn setTitle:[NSString stringWithFormat:#""] forState:UIControlStateNormal];
}
else
[btn setTitle:[NSString stringWithFormat:#"%i",self.presscount2] forState:UIControlStateNormal];
}
else if (btag == 3)
{
self.presscount3 ++;
[self.pressCountArray replaceObjectAtIndex:2 withObject:[NSNumber numberWithInt:self.presscount3]];
if (self.presscount3 > 3) {
self.presscount3 = 0;
[btn setTitle:[NSString stringWithFormat:#""] forState:UIControlStateNormal];
}
else
[btn setTitle:[NSString stringWithFormat:#"%i",self.presscount3] forState:UIControlStateNormal];
}
You can do something like this:
- (IBAction)pressCountBtn:(id)sender
{
UIButton * btn = (UIButton *)sender;
int btag = btn.tag;
int curCnt = [[self.pressCountArray objectAtIndex:btag] intValue];
curCnt ++;
if (curCnt > 3)
{
curCnt = 0;
[btn setTitle:[NSString stringWithFormat:#""] forState:UIControlStateNormal];
}
else {
[btn setTitle:[NSString stringWithFormat:#"%i",curCnt] forState:UIControlStateNormal];
}
[self.pressCountArray replaceObjectAtIndex:btag withObject:[NSNumber numberWithInt:curCnt]];
}
You'll just have to make sure that all objects in self.pressCountArray are NSNumbers, which you can easily do when you initialize the array.
Getting the button index from an array of buttons is easy.
- (IBAction)pressCountBtn:(id)sender
{
if ([sender isKindOfClass:[UIButton class]]) {
UIButton *thisButton = (UIButton *)sender;
NSUInteger indexOfButton = [yourButtonArray indexOfObject:thisButton];
if (indexOfButton != NSNotFound) {
// Now use this indexOfButton for whatever you want
}
}
}
create a strong array to hold the values(count) for each button tag.
NSInteger numberOfRows=3;
NSMutableArray *array=[[NSMutableArray alloc] initWithCapacity:numberOfRows];
Then ,
- (IBAction)pressCountBtn:(id)sender
{
UIButton * btn = (UIButton *)sender;
int btag = btn.tag;
//add count first time for tag
if([[array objectAtIndex:btag] valueForKey:#"COUNT"]==NULL){
[[array objectAtIndex:btag] setValue:#"1" forKey:#"COUNT"];
}else{
//get count from array
NSInteger count=[[[array objectAtIndex:btag] valueForKey:#"COUNT"] integerValue];
count+=count;
if (count> 3)
{
count = 0;
[btn setTitle:[NSString stringWithFormat:#""] forState:UIControlStateNormal];
}
else
[btn setTitle:[NSString stringWithFormat:#"%i",count] forState:UIControlStateNormal];
//write the updated count back to array
[[array objectAtIndex:btag] setValue:[NSString stringWithFormat:#"%d",count] forKey:#"COUNT"];
}
}
I am using the below function to add buttons same like Fred and No in the next line but no getting same button size and text at same place.
- (IBAction)addAnotherBranchField:(id)sender
{
NSLog(#"Add Another Branch");
UIView *superview = self;
_buttons = [NSMutableArray array];
self.translatesAutoresizingMaskIntoConstraints = NO;
self.backgroundColor = [UIColor clearColor];
_verticalButtonConstraints = [NSMutableArray array];
NSString* previousAnswer = [_datasource valueForField:_field.guid branchIndex:0];
id buttonForLoadedAnswer = nil;
for (FormListOption* option in _field.options) {
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.translatesAutoresizingMaskIntoConstraints = NO;
//Add a little padding around the text - Using edge insets does not play well with the autolayout so do it with a space instead
[button setTitle:[NSString stringWithFormat:#" %# ",option.text] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[_buttons addObject:button];
[superview addSubview: button];
if ([option.text isEqualToString:previousAnswer]) {
buttonForLoadedAnswer = button;
}
}
paddingCounter = paddingCounter + 100;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(200, paddingCounter, 32, 32)];
[addButton setImage:[UIImage imageNamed:#"nav_newanswers.png"] forState:UIControlStateNormal];
[addButton addTarget:self action:#selector(addAnotherBranchField:) forControlEvents:UIControlEventTouchUpInside];
[superview addSubview:addButton];
[superview bringSubviewToFront:addButton];
//Add the constraints
NSMutableDictionary* views = [NSMutableDictionary dictionary];
NSMutableString* visualLayout = [NSMutableString stringWithString:#"H:|-(5)-"];
for (NSInteger i=0; i < [_buttons count]; i++) {
NSString* name = [NSString stringWithFormat:#"button_%d", i];
[views setValue:[_buttons objectAtIndex:i] forKey:name];
[visualLayout appendFormat:#"[%#(>=80)]-", name];
}
[visualLayout appendString:#"(>=10)-|"];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:visualLayout
options:NSLayoutFormatAlignAllBottom
metrics:nil
views:views]];
}
- (void)updateVerticalConstrainsAgain:(UIView*)expandedView padding:(float)padding
{
[self removeConstraints:_verticalButtonConstraints];
[_verticalButtonConstraints removeAllObjects];
NSString* visualFormat = [NSString stringWithFormat: #"V:|[button]-(5)-%#|", expandedView ? [NSString stringWithFormat:#"[expanded]-(20)-"] : #""];
if (padding != 0 && expandedView == nil)
{
visualFormat = [NSString stringWithFormat:#"V:|[button(button)]-(%f)-|",padding];
}
for (UIView* button in _buttons) {
NSMutableDictionary* views = [NSMutableDictionary dictionaryWithObject:button forKey:#"button"];
if (expandedView) {
[views setObject:button forKey:#"expanded"];
}
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:visualFormat
options:0
metrics:nil
views:views];
[self addConstraints:constraints];
[_verticalButtonConstraints addObjectsFromArray:constraints];
}
}
Please explain me whaere i am getting wrong. spend my full day to get out from problems.
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.
Goodevening
Although i've read quite a lot related questions about adding a UIButton to a UIScrollView it doesn't work for me. When i use UIImages instead of UIButtons it works like a charm. What am i missing here? (don't mind the if's or for-loops, al those are correct, paths of images also)
for(int j = 0; j < [subcategorie count]; j++){
NSArray *product = [subcategorie objectAtIndex:(j)];
int posX = 0;
for(int k = 1; k <= [product count]; k++){
if((i-1) == currentCategory ){
//NSString *fotoName = [NSString stringWithFormat:#"images/product/%#/%#_%i.png",self.categorieen[(i-1)] ,self.categorieen[(i-1)] , k];
NSString *fotoName = [NSString stringWithFormat:#"%#_%i",self.categorieen[(i-1)] , k];
NSString *currentCategory = [NSString stringWithFormat:#"images/product/%#/", self.categorieen[(i-1)]];
NSString *path = [[NSBundle mainBundle] pathForResource:fotoName ofType:#"png" inDirectory:currentCategory];
UIButton *fotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[fotoButton setImage:[UIImage imageNamed:path] forState:UIControlStateNormal];
fotoButton.frame = CGRectMake(posX, 252, 718, 520);
fotoButton.backgroundColor = [UIColor clearColor];
self.scrollview.contentSize = CGSizeMake(posX, 252);
[self.scrollview setBounces:YES];
[self.scrollview setPagingEnabled:YES];
[self.scrollview addSubview:fotoButton];
[self.scrollview bringSubviewToFront:fotoButton];
[self.scrollview setUserInteractionEnabled:YES];
self.scrollview.userInteractionEnabled = YES;
[self addSubview: self.scrollview];
posX += 718;
NSLog(#"Fotolink = %#", fotoName);
}
}
}
Cheers
[UIImage imageNamed:path] looks incorrect,
try [UIImage imageWithData:[NSData dataWithContentsOfFile:path]
UIButton *fotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[fotoButton setImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:path] forState:UIControlStateNormal];