I have written the code shown below. my problem is that I can't touch some of the buttons. I have written that method in NSTimer method. Can anybody help in solving this problem?
One method is to create a button and another for changing the values to screen size.
-(void)createButton
{
int x=0;
int y=0;
int width=100;
int height=100;
for (int i=0; i<9; i++)
{
UIButton *button=[[UIButton alloc] initWithFrame:CGRectMake(x ,y, width, height)];
[button.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:24.0]];
NSDate *date=[NSDate date];
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:#"ss"];
NSString *sec=[dateformatter stringFromDate:date];
NSLog(#"sec is %#",sec);
CGPoint dest= CGPointMake(arc4random() %768, arc4random() %1024);
//CGPoint dest= CGPointMake(arc4random() %[sec intValue], arc4random() %480);
button.tag=i;
[button setBackgroundColor:[UIColor blackColor]];
[button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
[button setTitle:[NSString stringWithFormat:#"%d",i] forState:UIControlStateNormal];
//[button setImage:[UIImage imageNamed:#"thing.png"] forState:UIControlStateNormal];
int numx=[[NSNumber numberWithInt:dest.x]intValue];
int numy=[[NSNumber numberWithInt:dest.y]intValue];
//button.center.x= numx+5;
//button.center.y=numy+5;
button.center=CGPointMake(numx+10, numy+10);
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:[NSNumber numberWithInt:5] forKey:#"Xvalue"];
[dict setValue:[NSNumber numberWithInt:5] forKey:#"Yvalue"];
[dict setValue:button forKey:#"Button"];
[button addTarget:self action:#selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];
//[button addTarget:self action:#selector(dragBegan:withEvent:)forControlEvents: UIControlEventTouchDown];
//[button addTarget:#selector(buttonpressed:) action:#selector(buttonpressed:) forControlEvents:UIControlStateSelected];
[button addTarget:self action:#selector(dragMoving:withEvent:)forControlEvents: UIControlEventTouchDragInside];
[button addTarget:self action:#selector(dragEnded:withEvent:)forControlEvents: UIControlEventTouchUpInside |
UIControlEventTouchUpOutside];
[self.buttonArray addObject:dict];
[self.view addSubview:button];
[button release];
x+=50;
}
}
-(void)timerMethod
{
for(NSMutableDictionary *dict in self.buttonArray)
{
UIButton *but=[dict objectForKey:#"Button"];
CGPoint bcenter=but.center;
int numx=[[dict objectForKey:#"Xvalue"]intValue];
int numy=[[dict objectForKey:#"Yvalue"]intValue];
bcenter.x+=numx;
bcenter.y+=numy;
//bcenter.x=bcenter.x+[dict objectForKey:#"Xvalue"];
//bcenter.y=bcenter.y+[dict objectForKey:#"Yvalue"];
but.center=bcenter;
if(bcenter.x>720)
{
[dict setValue:[NSNumber numberWithInt:-10] forKey:#"Xvalue"];
}
if(bcenter.y>1000)
{
[dict setValue:[NSNumber numberWithInt:-10] forKey:#"Yvalue"];
}
if(bcenter.x<15)
{
[dict setValue:[NSNumber numberWithInt:10] forKey:#"Xvalue"];
}
if(bcenter.y<15)
{
[dict setValue:[NSNumber numberWithInt:10] forKey:#"Yvalue"];
}
}
}
-(void)buttonpressed:(id)sender
{
NSLog(#"sender tag is %d",[sender tag]);
}
try set target:self action:buttonpressed
I think you forget to do that , the function will be fired when you click it
[button addTarget:self action:#selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];
Related
I used to have a massive packed 8k+ line FeedViewController and anytime I wanted to change anything involving the look of statuses I had to change no less than a dozen viewcontrllers so I decided to try to refactor to follow a MVC type standard. I put most of the functionality in the tableviewcells so that I could just change the cell class instead of 12 files, now im hearing "you should keep your VIEWS dumb.....is this really so wrong?
//
// TriCornerFeedCell.m
//
//
#import "NSDate+TimeAgo.h"
#import "TriCornerFeedCell.h"
#import "AFNetworking.h"
#implementation TriCornerFeedCell
-(void)refreshGestureRecognizers{
while (self.gestureRecognizers.count) {
[self removeGestureRecognizer:[self.gestureRecognizers objectAtIndex:0]];
}
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(processDoubleTap:)];
doubleTap.numberOfTapsRequired = 2;
[self addGestureRecognizer:doubleTap];
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.3; //seconds
lpgr.delegate = self;
[self addGestureRecognizer:lpgr];
}
-(void)refreshCell{
_sdmanager = [SDWebImageManager sharedManager];
//Set Name Label
self.NameLabel.text=[NSString stringWithFormat:#"%# %#",self.statusObject.first_name,self.statusObject.last_name];
//Set Message Label
if(self.statusObject.message!=nil){
self.StatusLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
self.StatusLabel.text = self.statusObject.message;
self.StatusLabel.delegate = self;
[self checkForShoutoutsAndHashtags];
self.StatusLabel.lineBreakMode=0;
self.StatusLabel.numberOfLines=0;
//Cell.StatusLabel.text=[tempDictionary objectForKey:#"message"];
[self.StatusLabel sizeToFit];
}
//Set Date Label
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:self.statusObject.created];
self.timeLabel.text=[date timeAgo];
//Set Bump Views
if(self.statusObject.isBumped){
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_yellow.png"] forState:UIControlStateNormal];
}else{
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_grey.png"] forState:UIControlStateNormal];
}
self.bumpCount.text=[#(self.statusObject.bump_count) stringValue];
[self.bumpClearViewBtn addTarget:self action:#selector(bump:) forControlEvents:UIControlEventTouchUpInside];
[self.bumpCornerBG addTarget:self action:#selector(bump:) forControlEvents:UIControlEventTouchUpInside];
//Set Comment Related Views
if(self.statusObject.comment_count>0){
NSLog(#"COMMENT_COUNT:%d",self.statusObject.comment_count);
[self.commentCount setHidden:NO];
[self.miniCommentColorCircle setHidden:NO];
self.commentCount.text=[#(self.statusObject.comment_count) stringValue];
}else{
[self.commentCount setHidden:YES];
[self.miniCommentColorCircle setHidden:YES];
}
//Set Follow Btn Views
[self.followBtn.titleLabel setFont:[UIFont fontWithName:#"BloggerSans" size:14]];
[self.followBtn removeFromSuperview];
if(!self.statusObject.isFollowing){
[self.followBtn removeFromSuperview];
UIButton *followBtn= [[UIButton alloc] initWithFrame:CGRectMake(235, 16, 75, 25)];
[followBtn setImage:nil forState:UIControlStateNormal];
followBtn.layer.cornerRadius =2; // this value vary as per your desire
[followBtn.titleLabel setFont:[UIFont fontWithName:#"BloggerSans" size:14.0f]];
followBtn.titleEdgeInsets = UIEdgeInsetsMake(3, 0, 0, 0);
followBtn.clipsToBounds = YES;
[followBtn setTitleColor:[self colorWithHexString:#"ff68a8"] forState:UIControlStateNormal];
followBtn.layer.borderWidth=1.5f;
followBtn.layer.borderColor=[[self colorWithHexString:#"ff68a8"] CGColor];
[followBtn setTitle:#"Follow" forState:UIControlStateNormal];
[followBtn addTarget:self action:#selector(follow) forControlEvents:UIControlEventTouchUpInside];
self.followBtn=followBtn;
[self addSubview:self.followBtn];
}
//Reset icon to default in case default==nill
[self bringSubviewToFront:self.DefaultImgBorder];
[self bringSubviewToFront:self.DefaultImgBtn];
UIImage *noDefault = [UIImage imageNamed:#"female_mini_no_default_icon.png"];
[self.DefaultImgBtn setBackgroundImage:noDefault forState:UIControlStateNormal];
//Attempt to create hexagon cropped default photo
UIImage *hex_img = [UIImage imageNamed:#"big_hex_thumb.png"];
UIImage *tan=[UIImage imageNamed:#"feed_grey.png"];
UIImage *finalBG= [self maskImage:tan withMask:hex_img];
[self.DefaultImgBorder setImage:finalBG];
NSURL *thumb_url=[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",s3thumbURL,self.statusObject.thumb_img]];
#autoreleasepool {
[_sdmanager downloadWithURL:thumb_url
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize){}completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished){
if (image)
{
UIImage *thumbimg = image;
UIImage *hex_img = [UIImage imageNamed:#"big_hex_thumb.png"];
UIImage *noDefault = [UIImage imageNamed:#"female_mini_no_default_icon.png"];
[self.DefaultImgBtn setBackgroundImage:noDefault forState:UIControlStateNormal];
UIImage *finalImg= [self maskImage:thumbimg withMask:hex_img];
[self.DefaultImgBtn setBackgroundImage:finalImg forState:UIControlStateNormal ];
}
}];
}
[self.DefaultImgBtn removeTarget:nil
action:NULL
forControlEvents:UIControlEventAllEvents];
[self.DefaultImgBtn addTarget:self action:#selector(viewProfile:) forControlEvents:UIControlEventTouchUpInside];
//Misc Stuff
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
}
#pragma mark - Interaction Methods
-(void)follow{
[self.followSpinner removeFromSuperview];
[self.followBtn removeFromSuperview];
self.followSpinner = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStyleFadingCircleAlt color: [self colorWithHexString:#"b4b4b2"] spinnerSize:25];
[self.followSpinner setFrame:CGRectMake(260,15,30,30)];
self.spinner.tag=9;
[self addSubview:self.followSpinner];
[self.statusObject follow];
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (self.indexPath != nil && gestureRecognizer.state == UIGestureRecognizerStateBegan) {
NSString*loggedin_uid = [[NSUserDefaults standardUserDefaults] objectForKey:#"uid"];
if([self.statusObject.IMPORT_SOURCE isEqualToString:#"INSTAGRAM"] || [self.statusObject.IMPORT_SOURCE isEqualToString:#"TWITTER"]){
if([loggedin_uid isEqualToString:#"1"] || [loggedin_uid isEqualToString:#"2"]){
[self.delegate showImportAdminControls:self.indexPath];
}
}else{
if([loggedin_uid isEqualToString:#"1"] || [loggedin_uid isEqualToString:#"2"]){
[self.delegate showAdminControls:self.indexPath];
}else if ([self.statusObject.uid isEqualToString:loggedin_uid]){
[self.delegate deletePostAlert:self.indexPath];
}
}
}
}
- (void) processDoubleTap:(UITapGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateEnded)
{
if (self.indexPath)
{
self.statusObject.indexPath=self.indexPath;
if(!self.statusObject.isBumped){
int value = self.statusObject.bump_count+1;
self.statusObject.isBumped=YES;
self.statusObject.bump_count=value;
[self.bumpCount setText:[#(value) stringValue]];
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_yellow.png"] forState:UIControlStateNormal];
UIImageView *bumpBlowUpIcon=[[UIImageView alloc]initWithFrame:CGRectMake((self.frame.size.width/2)-5, (self.frame.size.height/2)-5, 10, 10)];
[bumpBlowUpIcon setImage:[UIImage imageNamed:#"heart_yellow.png"]];
bumpBlowUpIcon.alpha=.2;
[self addSubview:bumpBlowUpIcon];
[UIView animateWithDuration:.8 delay:0 usingSpringWithDamping:.3 initialSpringVelocity:.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
[bumpBlowUpIcon setFrame:CGRectMake((self.frame.size.width/2)-(self.frame.size.height/2), 0, self.frame.size.height, self.frame.size.height)];
bumpBlowUpIcon.alpha=.5;
}completion:^(BOOL finished) {
[bumpBlowUpIcon removeFromSuperview];
}];
}else{
int value = self.statusObject.bump_count-1;
self.statusObject.isBumped=NO;
self.statusObject.bump_count=value;
[self.bumpCount setText:[#(value) stringValue]];
[self.bumpCornerBG setBackgroundImage:[UIImage imageNamed:#"corner_bump_grey.png"] forState:UIControlStateNormal];
}
[self.statusObject bump];
}
}
}
-(void)viewProfile{
}
-(void)viewHashtag{
}
#pragma mark - Misc Methods
- (UIImage*) maskImage:(UIImage *) image withMask:(UIImage *) mask
{
CGImageRef imageReference = image.CGImage;
CGImageRef maskReference = mask.CGImage;
CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskReference),
CGImageGetHeight(maskReference),
CGImageGetBitsPerComponent(maskReference),
CGImageGetBitsPerPixel(maskReference),
CGImageGetBytesPerRow(maskReference),
CGImageGetDataProvider(maskReference),
NULL, // Decode is null
YES // Should interpolate
);
CGImageRef maskedReference = CGImageCreateWithMask(imageReference, imageMask);
CGImageRelease(imageMask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedReference];
CGImageRelease(maskedReference);
return maskedImage;
}
-(UIColor*)colorWithHexString:(NSString*)hex
{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];
// strip 0X if it appears
if ([cString hasPrefix:#"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor grayColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
#end
Ok. I've tried to merge all comments to a suitable answer.
When you want to stick to the MVC pattern you should keep your views as dumb as possible (regarding the coupling of view- and business-related components). In the best case they should not contain any business logic.
That implies that they also should not know anything about business objects (the model). As long as your statusObject in self.StatusLabel.text = self.statusObject.message; is anything else than a Data Transfer Object it is not a good idea to let the cells retrieve their values on their own - because then these cells would need to have knowledge about your model structure.
Usually each view does have its own view controller but - of course - you're allowed to compose your view controllers with functionality they need.
For example: if some view controllers need data you could introduce a separate (view related) component which will provide that data (e.g. by creating and returning cells). This component would be fed with your model data (or Data Transfer Objects) and would return a structure which could be used by all view controllers who need those information.
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.
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;
}