How to display Activity Indicator in song loading time in iOS - 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..

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

Loading overlay on collection view

I have a loading view that I insert over the top of a view while it is parsing data from the internet using a separate thread, in this case its on top of a UICollectionView.
For some reason that I cannot understand the loading overlay disappears on its own whist the parsing is still taking place, presenting a blank screen for a second or two. It doesn't seem to happen on UITableViews just on UIcollectionviews. Any help would be appreciated.
Activity overlay.m:
#import "ActivityOverlayController.h
#interface ActivityOverlayController ()
#end
#implementation ActivityOverlayController
-(id)initWithFrame:(CGRect)theFrame {
if (self = [super init]) {
frame = theFrame;
self.view.frame = theFrame;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#", #"ActivityOverlayController called");
container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
activityLabel = [[UILabel alloc] init];
activityLabel.text = NSLocalizedString(#"Loading", #"string1");
activityLabel.textColor = [UIColor lightGrayColor];
activityLabel.font = [UIFont boldSystemFontOfSize:17];
[container addSubview:activityLabel];
activityLabel.frame = CGRectMake(0, 3, 70, 25);
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.color = [UIColor blackColor];
activityIndicator.hidesWhenStopped = TRUE;
[activityIndicator startAnimating];
activityIndicator.frame = CGRectMake(80, 0, 30, 30);
[container addSubview:activityIndicator];
[self.view addSubview:container];
container.center = CGPointMake(frame.size.width/2, frame.size.height/2);
self.view.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.7];
}
-(void)viewWillAppear:(BOOL) animated {
[super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL) animated {
[super viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[activityIndicator stopAnimating];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Parsing part of collectionViewController.m:
-(void)ParseCollectionView{
[self performSelectorOnMainThread:#selector(showActivityView) withObject:nil waitUntilDone:YES];
CollectionViewImages = [[NSMutableArray alloc]init];
NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:GalleryTitle]];
cvTBXML = [[TBXML alloc]initWithXMLData:xmlData];
// Obtain root element
TBXMLElement * root = cvTBXML.rootXMLElement;
TBXMLElement * channel = [TBXML childElementNamed:#"channel" parentElement:root];
if (root)
{
TBXMLElement * item = [TBXML childElementNamed:#"item" parentElement:channel];
while (item !=nil)
{
//create new instance of news object
NSObject *Imagetoparse = [[GalleryImage alloc] init];
TBXMLElement * link = [TBXML childElementNamed:#"link" parentElement:item];
NSString *linktext= [TBXML textForElement:link];
[Imagetoparse setValue:linktext forKey:#"link"];
TBXMLElement * thumbnail = [TBXML childElementNamed:#"description" parentElement:item];
NSString *Thumbnailtext= [TBXML textForElement:thumbnail];
Thumbnailtext = [Thumbnailtext substringFromIndex:21];
NSInteger *slength = Thumbnailtext.length -4;
Thumbnailtext = [Thumbnailtext substringToIndex:slength];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#"thumb" withString:#"main"];
NSLog(#"Thumnail1 : %#", Thumbnailtext);
NSData *Thumbnailimage = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: Thumbnailtext]];
[Imagetoparse setValue:Thumbnailimage forKey:#"thumbnail"];
[CollectionViewImages addObject:Imagetoparse];
item = [TBXML nextSiblingNamed:#"item" searchFromElement:item];
}
}
[self.collectionView reloadData];
NSLog(#"%#", #"Finished Parse Collection View");
[self performSelectorOnMainThread:#selector(hideActivityView) withObject:nil waitUntilDone:NO];
}
-(void)showActivityView {
if (overlayController == nil) {
overlayController = [[ActivityOverlayController alloc] initWithFrame:(self.view.superview.bounds)];
}
[self.view.superview insertSubview:overlayController.view aboveSubview:self.view];
}
-(void)hideActivityView {
[overlayController.view removeFromSuperview];
}

Horizontal scrolling on a view in ios [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I implement scroll view to horizontally scroll the view pages loaded from a NSDictionary. Presently i am using swipegesture but that is little slow.
What code should I implement to achieve horizontal scrolling?
i am using this code:
-(void)DownLoadData:(NSString *)indexSelect
{
{
[[SharedUtilities getInstance]AddActivityIndicatorViewOnMainThread:self.view];
}
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)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:#""])
{
// strg=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"image"]];
_imageView1.hidden=YES;
// _txtView.frame=CGRectMake(4.0f,95.0f,310.0f,100.0f );
_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,_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._publicationDate setText:[Dic valueForKey:#"PUB_DATE"]];
[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=#"";
}
NSString *city;
if ([[Dic valueForKey:#"REPORTING_CITY"] length]>2)
{
city=[NSString stringWithFormat:#", %#",[Dic valueForKey:#"REPORTING_CITY"]];
}
else
{
city=#"";
}
NSString *str = [NSString stringWithFormat:#"%#ee%#", writer,city];
//[cell._Writer setText: [tempDic valueForKey:#"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];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_titleLabel = [[UILabel alloc] init];
lblTitle.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:20];
lblTitle.text=_strTitle;
NSLog(#"arrUrls %d",[_arrUrlLinks count]);
NSLog(#"strCurrentNewsSelect %#",_strCurrentNewsSelect);
[[NSNotificationCenter defaultCenter]
postNotificationName:#"DISABLEGESTURE"
object:self];
count=[_strCurrentNewsSelect integerValue];
[self performSelectorInBackground:#selector(DownLoadData:) withObject:_strCurrentNewsSelect];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
}
_lblNewsCount.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:16];
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",[_strCurrentNewsSelect integerValue]+1,[_arrUrlLinks count]];
// Do any additional setup after loading the view from its nib.
UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(280, 340, 40, 40)];
[shareBtn addTarget:self action:#selector(Share:) forControlEvents:UIControlEventTouchUpInside];
[shareBtn setBackgroundImage:[UIImage imageNamed:#"share1.png"] forState:UIControlStateNormal];
// [self.view addSubview:shareBtn];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
}
if([_strCurrentNewsSelect isEqualToString:[NSString stringWithFormat:#"%d",[_arrUrlLinks count]-1]])
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(rightSwipeHandle:)];
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(leftSwipeHandle:)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
}
-(IBAction)Share:(UIButton *)sender
{
NSLog(#"SHare called =%d",sender.tag);
// NSDictionary *tempDic = [[self._resultDic valueForKey:#"items"] objectAtIndex:sender.tag];
[[SharedUtilities getInstance] set_LinkForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"image"]];
[[SharedUtilities getInstance]set_headerForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"header"]];
[[SharedUtilities getInstance]set_viewController:self];
[[SharedUtilities getInstance]Share];
}
-(IBAction)btnBackPress:(id)sender;
{
[[NSNotificationCenter defaultCenter]
postNotificationName:#"ENABLEGESTURE"
object:self];
[self.navigationController popViewControllerAnimated:YES];
lblTitle.text=_strTitle;
}
-(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;
}
}
-(IBAction)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]];
}
}
}
Have you tried as like below methods,
UIScrollView * _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 10.0, 320.0, 280.0)];
_scrollView.backgroundColor = [UIColor clearColor];
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
[self addSubview:_scrollView];
float width = 0.0;
for (int i = 0; i < pageCount; i++)
{
UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake((i * 320.0) + 20.0, 0.0, 280.0, 280.0);
[_scrollView addSubview:yourView];
width = yourView.frame.size.width + yourView.frame.origin.x + 20.0;
}
[_scrollView setContentSize:CGSizeMake(width, _scrollView.frame.size.height)];
Look at UIScrollView. To be honest this question makes it look like you've done very little research into the problem though. Can you tell us a bit more about what you currently have and what you've done so far?
UIScrollView Scroll depends on the ContentSize. So you have to set the ContentSize.
For Horizinatal Scrolling
[scroll setContentSize:CGSizeMake(1500, scroll.frame.size.height)];

Print multiple pages iOS and one pdf

I have the following code which print 2 pdfs when there's more content/graphics than one page, but I want 1 pdf with 2 pages. What do I have to change?
It's made in Xcode for iOS 5 and higher.
I have the following code which print 2 pdfs when there's more content/graphics than one page, but I want 1 pdf with 2 pages. What do I have to change?
-(void) addPrintView {
UIView* v = nil;
if([printViews lastObject] != nil) {
UIView* lastSubView = [printViews lastObject];
v = [[UIView alloc] initWithFrame:CGRectMake(0, lastSubView.frame.origin.y + lastSubView.frame.size.height, 824, 1265)];
} else {
v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 824, 1265)];
}
[v setOpaque:YES];
[v setBackgroundColor:[UIColor whiteColor]];
[printViews addObject:v];
[self.scrollView addSubview:v];
[self.scrollView setContentSize:CGSizeMake(824, (1265*[printViews count])+220) ];
//add pagenumber
UILabel *lblPageNumber = [[UILabel alloc] initWithFrame:CGRectMake(824 - 30, 1265 - 50 , 30, 30)];
lblPageNumber.text = [NSString stringWithFormat:#"%i", printViews.count];
lblPageNumber.font = [UIFont systemFontOfSize:12];
lblPageNumber.tag = 1000 + [printViews count];
[lblPageNumber setHidden:YES];
[_pageNumbers addObject:lblPageNumber];
}
- (IBAction)printContent:(id)sender {
if(!self.orderOperationCenter.order.signature){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Signature" message:#"Please provide a signature" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
return;
}
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
[self.btnFinish setHidden:YES];
[self.btCancel setAlpha:0];
});
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = #"Versmissen";
printInfo.duplex = UIPrintInfoDuplexNone;
pic.printInfo = printInfo;
pic.printFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0);
pic.printFormatter.maximumContentWidth = 6 * 72.0;
pic.printInfo.orientation = UIPrintInfoOrientationPortrait;
pic.showsPageRange = YES;
NSMutableArray* arr = [[NSMutableArray alloc] init];
for(int i = 0; i < printViews.count; i++){
UIView* v = [printViews objectAtIndex:i];
[v addSubview:[_pageNumbers objectAtIndex:i]];
[arr addObject:[UIImage imageWithView:v]];
}
[pic setPrintingItem:arr];
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
if (!completed && error)
NSLog(#"FAILED! due to error in domain %# with error code %u",
error.domain, error.code);
};
[pic presentFromBarButtonItem:self.printButton animated:YES completionHandler:completionHandler];
}
-(void)printInteractionControllerDidFinishJob:(UIPrintInteractionController *)printInteractionController {
UIAlertView* view = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Succesfully printed the order overview." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[view show];
[self.btnFinish setHidden:NO];
for(UIView* v in _pageNumbers){
[v removeFromSuperview];
}
[self.btCancel setAlpha:1];
}
-(UIPrintPaper *)printInteractionController:(UIPrintInteractionController *)printInteractionController choosePaper:(NSArray *)paperList {
CGSize size = [[printViews lastObject] frame].size;
return [UIPrintPaper bestPaperForPageSize:size withPapersFromArray:paperList];
}

Removing subviews programmatically

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

Resources