Removing subviews programmatically - ios

I got this code inside my didReceiveRemoteNotification: method in appdelegate
I would like to know how can I remove this subviews using a delay, it is supposed the subviews show info from a push notification but I want them to disappear after 3.5 seconds(delay2)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
// Create the UILabel instance
CGRect myFrame = CGRectMake(0, 20, 320, 50);
UIView *myView = [[UIView alloc] initWithFrame:myFrame];
myView.backgroundColor = [UIColor blueColor];
[self.window addSubview:myView];
[myView release];
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 300, 20)];
[aLabel setText:alert];
[self.window addSubview:aLabel];
[aLabel release];
NSString *path = [[NSBundle mainBundle] pathForResource:#"sound"ofType:#"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
//SONAR//
[self performSelector:#selector(delay2) withObject:nil afterDelay:3.5];
}
-(void)delay2 {
NSString *path = [[NSBundle mainBundle] pathForResource:#"sound"ofType:#"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
}

You can use removeFromSuperview instance method of UIView.
While adding views on window set tag to all. And in delay2 method remove them using tag & removeFromSuperview method.
CGRect myFrame = CGRectMake(0, 20, 320, 50);
UIView *myView = [[UIView alloc] initWithFrame:myFrame];
myView.backgroundColor = [UIColor blueColor];
[myView setTag:999];
[self.window addSubview:myView];
[myView release];
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 300, 20)];
[aLabel setText:alert];
[aLabel setTag:999];
[self.window addSubview:aLabel];
[aLabel release];
-(void)delay2 {
for(UIView *subView in window.subviews)
{
if(subView.tag == 999)
[subView removeFromSuperview];
}
}

Related

How to add textfield in scrollview in ios?

I am making an app in which i am selecting photos from gallery and I want that on every picture or video one textfield will appear so that if i want to describe about that pic or video.
here is the code of display the photos but not showing the textfield on above the every pic in scrollview.
-(void)launchController
{
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc]initImagePicker];
elcPicker.maximumImagesCount = 100;
elcPicker.returnsOriginalImage = YES;
elcPicker.returnsImage = YES;
elcPicker.onOrder = YES;
elcPicker.mediaTypes = #[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
elcPicker.imagePickerDelegate = self;
[self presentViewController:elcPicker animated:YES completion:Nil];
}
-(void)launchSpecialController
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
self.specialLibrary = library;
NSMutableArray *groups = [NSMutableArray array];
[_specialLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group , BOOL *stop){
if(group){
[groups addObject:group];
}else{
[self displayPickerForGroup:[groups objectAtIndex:0]];
}
} failureBlock:^(NSError *error) {
chosenImages = nil;
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
NSLog(#"A problem occured %#", [error description]);
// an error here mean
}];
}
- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithStyle:UITableViewStylePlain];
tablePicker.singleSelection = YES;
tablePicker.immediateReturn = YES;
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
elcPicker.maximumImagesCount = 1;
elcPicker.imagePickerDelegate = self;
elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
elcPicker.onOrder = NO; //For single image selection, do not display and return order of selected images
tablePicker.parent = elcPicker;
tablePicker.assetGroup = group;
[tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
[self presentViewController:elcPicker animated:YES completion:nil];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
return YES;
}else{
return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
}
#pragma mark ELCImageControllerDelegate Methods
-(void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
imageScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, 450)];
[self.view addSubview:imageScroll];
UITextField *textfield1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, 100, 40)];
textfield1.backgroundColor = [UIColor greenColor];
NSMutableArray *textfieldArray = [NSMutableArray arrayWithCapacity:[info count]];
[textfieldArray addObject:textfield1];
textfield1.text= #"hello";
[imageScroll addSubview:textfield1];
for(UIView *v in [imageScroll subviews]){
[v removeFromSuperview];
}
CGRect workingFrame = imageScroll.frame;
workingFrame.origin.x = 0;
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
for (NSDictionary *dict in info) {
if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[imageScroll addSubview:imageview];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
} else {
NSLog(#"UIImagePickerControllerReferenceURL = %#", dict);
}
} else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[imageScroll addSubview:imageview];
;
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
} else {
NSLog(#"UIImagePickerControllerReferenceURL = %#", dict);
}
} else {
NSLog(#"Uknown asset type");
}
}
chosenImages = images;
[imageScroll setPagingEnabled:YES];
[imageScroll setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad {
//chosenImages = [[NSArray alloc]init];
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
// textfield1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, 100, 40)];
// textfield1.backgroundColor = [UIColor greenColor];
// textfieldArray = [NSMutableArray arrayWithCapacity:[info count]];
// [textfieldArray addObject:textfield1];
// textfield1.text= #"hello";
// [imageScroll addSubview:textfield1];
UIButton *uploadimage = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 55, 55)];
uploadimage.backgroundColor = [UIColor blueColor];
[uploadimage setTitle:#"multiple images" forState:UIControlStateNormal];
[uploadimage addTarget:self action:#selector(launchSpecialController) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:uploadimage];
UIButton *singleimage = [[UIButton alloc]initWithFrame:CGRectMake(90, 30, 55, 55)];
singleimage.backgroundColor = [UIColor blueColor];
[singleimage setTitle:#"uploadimage" forState:UIControlStateNormal];
[singleimage addTarget:self action:#selector(launchController) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:singleimage];
imagePicker = [[UIImagePickerController alloc]init];
I don't understand your code lines. The problem should be there.
Why are you doing below things?
[imageScroll addSubview:textfield1];
for(UIView *v in [imageScroll subviews]){
[v removeFromSuperview];
}
In first line you are adding textfield to your scrollview and then you are using for loop to remove all subviews. It will remove your textfield from scrollview as well. You should not do this if you want to show textfield to user.
Please try by commenting the for loop. Hope it will work for you.
//Edit begins over here.
I think you should use UICollectionView instead of UIScrollView. In each and every cells of collectionview, you can show image and textfileds. It will be easy for you and also it will look better.
Thanks
Use NSMutableArray store UITextField value in it and call it with image array with function on the same button.
NSMutableArray *arr = [NSMutablearray....];
for (UIView *subV in self.view.subviews){
if([subV isKindOfClass:[UITextField class]])
{
//store it in a NSDictionary, so later can still know which
//textField your text belongs,
NSDictionary *tempDic = [NSDictionary dictionaryWithObjectAndKey:subV.txt
,subV.tag,/*or subVw.placeholder*/,nil];
[arr addObject:tempDic];
}
}

iOS - Navigation Title comes from left when back button is pressed

In my app when I visit certain view controllers and touch the Back button in the navigation bar, the navigation title of the resulting viewcontroller looks to be coming from the upper left corner and it looks ugly.
A picture of such an instance is shown below.
I have set the titles programatically.
Can somebody please tell me why this is happening and how I could fix it? Thanks in advance.
Here is my code:
ViewController B
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,120,45)] ;
label.textColor = COLOR_TEXT_NAVIGATION_BAR_COLOR;
label.backgroundColor = [UIColor clearColor];
label.font = FONT_NAVIGATION_TITLE_BAR;
label.text = [NSString stringWithFormat:PAGE_TITLE_ADD_SERVICE_PROVIDER];
self.navigationItem.titleView = label;
[label sizeToFit];
UIButton *homeButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 20, 20)];
[homeButton setImage:[UIImage imageNamed:IMG_HOME_MENU_BUTTON] forState:UIControlStateNormal];
[homeButton addTarget:self action:#selector(homeMenuAction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:homeButton];
accNumTextFiled.delegate=self;
nameTextFiled.text = addPayee.providerName;
payLimitTextFiled.text = [NSString stringWithFormat:#"%9.2f", addPayee.paymentLimit];//[NSString stringWithFormat:#"%f",addPayee.paymentLimit];
descTextFiled.text = addPayee.description;
catTextFiled.text = addPayee.maincategory;
subCatTextFiled.text = addPayee.subcategory;
accNumTextFiled.text = addPayee.paymentAccountNumber;
[accNumTextFiled setKeyboardType:UIKeyboardTypeNumberPad];
[self labelCss];
scrollView.contentSize=CGSizeMake(320,450);
}
ViewController A
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = COLOR_BG_INNER_PAGE_COLOR;
NSArray *mappingObjArray1 = #[#"providerName",#"description",#"paymentLimit",#"providerCode",#"maincategory",#"subcategory"];
NSDictionary *queryParams = #{};
commonRestDataMapping = nil;
commonRestDataMapping = [[CommonRestDataMapping alloc] init];
commonRestDataMapping.restDataMappingDelegate = self;
commonRestDataMapping.servicePath = REST_WEB_SERVICE_ADD_PAYEE_LIST;
commonRestDataMapping.mappingObjArray = mappingObjArray1;
commonRestDataMapping.mappingClassString = #"AddPayee";
commonRestDataMapping.mappingKeyPath = #"data";
commonRestDataMapping.mappingQueryParams = queryParams;
[commonRestDataMapping configureRestKit];
[commonRestDataMapping loadDataArray];
if ([self respondsToSelector:#selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone;
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[super createNavigationBar:USER_ACCOUNT_PAGE];
[super setNavihationTitle:PAGE_TITLE_ADD_PAYEE];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//WEB service data initilization
[[WebServiceUrl getSharedInstance] dataiInitialize];
[GMSServices provideAPIKey:#"AIzaSyCBfhnMtcmdhJaaqff72PlvJIjBTZpfSu4"];
NSString* docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString* dbPath = [docPath stringByAppendingPathComponent:#"datadb.sqlite"];
NSFileManager *fm = [NSFileManager defaultManager];
// Check if the database is existed.
if(![fm fileExistsAtPath:dbPath])
{
// If database is not existed, copy from the database template in the bundle
NSString* dbTemplatePath = [[NSBundle mainBundle] pathForResource:#"datadb" ofType:#"sqlite"];
NSError* error = nil;
[fm copyItemAtPath:dbTemplatePath toPath:dbPath error:&error];
if(error){
NSLog(#"can't copy db.");
} else{
NSLog(#" copy db.");
}
} else {
NSLog(#" db exsists");
}
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
UIView *addStatusBar = [[UIView alloc] init];
addStatusBar.frame = CGRectMake(0, 0, 1024, 20);
addStatusBar.backgroundColor = [UIColor blackColor]; //change this to match your navigation bar
[self.window.rootViewController.view addSubview:addStatusBar];
}
homeViewController = [[HomeViewController alloc] initWithNibName:#"HomeViewController" bundle:nil];
UINavigationController *myNav1=[[UINavigationController alloc] initWithRootViewController:homeViewController];
UIImage *navBackgroundImg = [UIImage imageNamed:#"aa1.png"];
[myNav1.navigationBar setBackgroundImage:navBackgroundImg forBarMetrics:UIBarMetricsDefault];//iOS 5 only
// Override point for customization after application launch.
self.viewController = myNav1;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)transitionToViewController:(UIViewController *)viewController
withTransition:(UIViewAnimationOptions)transition
{
[UIView transitionFromView:self.window.rootViewController.view
toView:viewController.view
duration:0.35f
options:transition
completion:^(BOOL finished){
self.window.rootViewController = viewController;
}];
}

How to display Activity Indicator in song loading time in iOS

I am working Audioplayer functionality.I am using AVAudioplayer framework.i have some problem.i want to put an activity indicator view in song loading time.so that when you touch the play it starts the activity indicator view and when the audio starts, the activity indicator stops.That is my requirement.i am writing some code.But it is not working fine for me.help me any body.
-(void)viewDidLoad {
[self temp];
[self loadData];
loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(94, 28, 130, 22)];
loadingLabel.backgroundColor = [UIColor clearColor];
loadingLabel.textColor = [UIColor blackColor];
[loadingLabel setFont:[UIFont systemFontOfSize:10.0]];
loadingLabel.adjustsFontSizeToFitWidth = YES;
loadingLabel.textAlignment = NSTextAlignmentCenter;
loadingLabel.text = #"loading In...";
loadingLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
}
-(void)temp {
// loading View
loadingView=[[UILabel alloc]initWithFrame:CGRectMake(135, 200, 40, 40)];
loadingView.backgroundColor=[UIColor clearColor];
loadingView.clipsToBounds=YES;
loadingView.layer.cornerRadius=10.0;
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityView.tag=960;
activityView.frame = CGRectMake(10, 11, activityView.bounds.size.width, activityView.bounds.size.height);
[loadingView addSubview:activityView];
}
-(void)playOrPauseButtonPressed:(id)sender {
if(playing==NO)
{
[playButton setBackgroundImage:[UIImage imageNamed:#"Pause.png"] forState:UIControlStateNormal];
// Here Pause.png is a image showing Pause Button.
NSError *err=nil;
if (!audioPlayer)
{
audioSession=[AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSLog(#"%# %d",urlsArray,selectedIndex);
NSString *sourcePath=[urlsArray objectAtIndex:selectedIndex];
NSData *objectData=[NSData dataWithContentsOfURL:[NSURL URLWithString:sourcePath]];
NSLog(#"%#",objectData);
audioPlayer = [[AVAudioPlayer alloc] initWithData:objectData error:&err];
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[loadingView addSubview:activityView];
[loadingView addSubview:loadingLabel];
[self.view addSubview:loadingView];
[activityView startAnimating];
[self.view addSubview:loadingView];
}
if(err)
{
NSLog(#"Error %ld,%#",(long)err.code,err.localizedDescription);
}
NSTimeInterval bufferDuration=0.005;
[audioSession setPreferredIOBufferDuration:bufferDuration error:&err];
if(err)
{
NSLog(#"Error %ld, %#", (long)err.code, err.localizedDescription);
}
double sampleRate = 44100.0;
[audioSession setPreferredSampleRate:sampleRate error:&err];
if(err)
{
NSLog(#"Error %ld, %#",(long)err.code,err.localizedDescription);
}
[audioSession setActive:YES error:&err];
if(err)
{
NSLog(#"Error %ld,%#", (long)err.code, err.localizedDescription);
}
sampRate=audioSession.sampleRate;
bufferDuration=audioSession.IOBufferDuration;
NSLog(#"SampeRate:%0.0fHZI/OBufferDuration:%f",sampleRate,bufferDuration);
audioPlayer.numberOfLoops = 0;
[audioPlayer prepareToPlay];
[audioPlayer play];
audioPlayer.delegate=self;
if(!audioPlayer.playing)
{
[audioPlayer play];
}
playing=YES;
}
else if (playing==YES)
{
[playButton setBackgroundImage:[UIImage imageNamed:#"play12.png"] forState:UIControlStateNormal];
[audioPlayer pause];
playing=NO;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateViewForPlayerState) userInfo:nil repeats:YES];
}
if (self.audioPlayer)
{
[self updateViewForPlayerInfo];
[self updateViewForPlayerState];
[self.audioPlayer setDelegate:self];
}
}
-(void)loadData
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[self.view addSubview:loadingView];
[activityView startAnimating];
loadingConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
[activityView stopAnimating];
[loadingView removeFromSuperview];
}
you can crate loading custom loading view like bellow..
-(void) showLoadingView
{
CGRect screenRect = [UIScreen mainScreen].bounds;
if (loadingView == nil)
{
loadingView = [[UIView alloc] initWithFrame:screenRect];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor darkGrayColor];
loadingView.alpha = 0.5;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.window.center.x-18.0,self.window.center.y-18.0, 37.0, 37.0)];
[spinningWheel startAnimating];
spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
spinningWheel.alpha = 1.0;
[loadingView addSubview:spinningWheel];
[spinningWheel release];
}
[window addSubview:loadingView];
}
-(void) showLoadingViewMessage:(NSString *)msg
{
CGRect screenRect = [UIScreen mainScreen].bounds;
if (loadingView == nil)
{
loadingView = [[UIView alloc] initWithFrame:screenRect];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor darkGrayColor];
loadingView.alpha = 0.5;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.window.center.x-18.0, self.window.center.y-18.0, 37.0, 37.0)];
[spinningWheel startAnimating];
spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
spinningWheel.alpha = 1.0;
[loadingView addSubview:spinningWheel];
[spinningWheel release];
}
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 250.0, 320.0, 80.0)];
lblTitle.text = msg;
lblTitle.textAlignment = UITextAlignmentCenter;
lblTitle.textColor = [UIColor whiteColor];
lblTitle.alpha = 1.0;
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.numberOfLines = 0;
//lblTitle.layer.borderColor = [UIColor blueColor].CGColor;
//lblTitle.layer.borderWidth = 1.0;
[loadingView addSubview:lblTitle];
[lblTitle release];
[window addSubview:loadingView];
}
-(void) hideLoadingView
{
if(loadingView)
{
[loadingView removeFromSuperview];
loadingView = nil;
}
}
put that all three methods in your AppDelegate and Call the showLoadingView whenevery you whant loading and call hideLoadingView whenever You dont want .
i hope it is helpful for you..

Setting UIView tags with int values but not get the same tag value back

I have a UIView that are menuiitems and these menu items are dynamically created where i stamp each uiview tag by increment of 1, but when i want to retrieve the uiview tag values when the user clicks on the menu item i get a different tag number.
I want to retrieve the tag which has the id stored so that i can post that id to a php script.
How do i retrieve the tags form when i set them?
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
UIView *tempView = recognizer.view;
NSNumber *tag = [NSNumber numberWithInt:tempView.tag];
int idCat = [tag intValue];
NSLog(#"TAG %d", idCat);
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:
#"http://localhost:8888/MAMP/WHFC/SubCategories.php?categoryid=%d", idCat]]];
int i = 0;
NSError *e;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
NSArray *arrCategoryList =
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&e];
UIViewController *viewController = [[UIViewController alloc] init];
viewController.view.backgroundColor = [UIColor whiteColor];
UIView *uiView = [[UIView alloc] init];
[uiView setFrame:CGRectMake(0, 480, 320, 480)];
[uiView setBackgroundColor:[UIColor grayColor]];
viewController.view = uiView;
UITableView *uiTableView = [[UITableView alloc] init];
[uiTableView setFrame:CGRectMake(0, 0, 320, 480)];
[uiView addSubview:uiTableView];
[self presentViewController:viewController animated:YES completion:nil];
}
This is the code that creates the menu items in another view:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: #"http://localhost:8888/MAMP/WHFC/categories.php"]];
int i = 0;
NSError *e;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
NSArray *arrCategoryList = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&e];
for(NSDictionary *dictCategory in arrCategoryList)
{
NSString *strCategoryId = [dictCategory objectForKey:#"CategoryId"];
NSString *strCategoryName = [dictCategory objectForKey:#"Name"];
NSLog(#"%# : %#",strCategoryId,strCategoryName);
UIView *linkMenu = [[UIView alloc] init];
[linkMenu setFrame:CGRectMake(10, i+1, 300, 35)];
linkMenu.tag = [NSString stringWithFormat:#"%d", strCategoryId];
linkMenu.layer.zPosition = 1;
[viewSlide3 addSubview:linkMenu];
[linkMenu setBackgroundColor:[UIColor blueColor]];
linkMenu.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.9];
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(handleSingleTap:)];
[linkMenu addGestureRecognizer:singleFingerTap];
UILabel *labelMenu = [[UILabel alloc] init];
[labelMenu setFrame:CGRectMake(20, 0, 300, 35)];
[labelMenu setFont:[UIFont systemFontOfSize:16]];
[labelMenu setTextColor:[UIColor whiteColor]];
[linkMenu addSubview:labelMenu];
[labelMenu setText:strCategoryName];
i = i + 35 + 1;
}
If you have a UIView lets say A inside which are placed all the other menu items which are also UIViews lets say B, C, and D then most probably the recognizer.view is returning you A no matter which of the B, C, or D are pressed.
Write this in your handleSingleTap function:
CGPoint touchPoint=[gesture locationInView:scrollView];
for(UIView * subView in myView ) //here myView should be the superView A where you have added all the menu item view B, C, and D
{
if(CGRectContainsPoint(subView.bounds, touchPoint))
{
NSNumber *tag = [NSNumber numberWithInt:subView.tag];
}
}
That tag variable will have your final tag that you need.

iOS scrollview adaption for landscape

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

Resources