I have a imageView embedded in a scrollView. The imageView needs to be downloaded from the Internet (through flickr api), so I add a thread to handle this. But what am I supposed to do after I finished downloading the image? How can I reload my imageView?Here's my code.
In fact, it is working fine. but the imageView's size is (0, 0). How can I fix that?
- (void)viewDidLoad
{
[super viewDidLoad];
if (!self.myImage)
{
UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[spinner startAnimating];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:spinner];
dispatch_queue_t downloadQueue = dispatch_queue_create("flickr downloader (photo)", NULL);
dispatch_async(downloadQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:[FlickrFetcher urlForPhoto:self.photo format:FlickrPhotoFormatLarge]];
dispatch_async(dispatch_get_main_queue(), ^{
self.myImage = [UIImage imageWithData:data];
[self.imageView setImage:self.myImage];
[self viewDidLoad];
[self viewWillAppear:NO];
NSLog(#"imageViewSet!");
self.navigationItem.rightBarButtonItem = nil;
});
});
dispatch_release(downloadQueue);
}
else
{
NSString* imageTitle;
if ([[self.photo objectForKey:#"title"] length] > 0)
imageTitle = [self.photo objectForKey:#"title"];
else if ([[self.photo valueForKeyPath:#"description._content"] length] > 0)
imageTitle = [self.photo valueForKeyPath:#"description._content"];
else imageTitle = #"Unknown";
[[self navigationItem] setTitle:imageTitle];
self.scrollView.delegate = self;
self.scrollView.contentSize = self.imageView.image.size;
}
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
double scale = self.imageView.bounds.size.width * 1.0 / self.myImage.size.width;
if (scale > self.imageView.bounds.size.height * 1.0 / self.myImage.size.height)
scale = self.imageView.bounds.size.height * 1.0 / self.myImage.size.height;
NSLog(#"imgview%g, %g",self.imageView.bounds.size.width, self.imageView.bounds.size.height);
NSLog(#"img%g, %g",self.myImage.size.width, self.myImage.size.height);
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
[self.scrollView setZoomScale:scale];
}
The usual way is to call:
[self.imageView setNeedsDisplay];
Edited to Add:
I just realized you said the image view is still (0,0). From the docs :
Setting the image property does not change the size of a UIImageView.
Call sizeToFit to adjust the size of the view to match the image.
Related
I have built an iPhone app with a page to show the contents of a .txt file in UIScrollView. For some reason my plain txt file causes the Scrollview to allow it to pan slightly to the left and right, I want it to be solid up down scrolling only.
Really need help with this one..
Thanks
#import "ITFAQController.h"
#import "FTCoreTextView.h"
#implementation ITFAQController
- (NSString *)textForView {
NSString *path = [[NSBundle mainBundle] pathForResource:#"faq" ofType:#"txt"];
NSError *error;
return [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
}
/*- (id)init
{
self = [super init];
if (self) {
// Custom initialization
[self showLogoInNavBar:YES];
}
return self;
}
*/
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
[self showLogoInNavBar:YES];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 330, (self.view.bounds.size.height - 90))];
[self.view addSubview:scrollView];
FTCoreTextView *ctView = [[FTCoreTextView alloc] initWithFrame:CGRectMake(10, 0, 300, scrollView.bounds.size.height)];
[ctView setText:[self textForView]];
FTCoreTextStyle *defaultStyle = [FTCoreTextStyle styleWithName:FTCoreTextTagDefault];
[defaultStyle setFont:kITDescriptionFont];
[defaultStyle setTextAlignment:FTCoreTextAlignementJustified];
[defaultStyle setParagraphInset:UIEdgeInsetsMake(5, 10, 0, 0)];
[ctView addStyle:defaultStyle];
FTCoreTextStyle *title = [FTCoreTextStyle styleWithName:#"title"];
[title setFont:kITTitleFont];
[title setColor:kITCellFontColor];
[title setParagraphInset:UIEdgeInsetsMake(10, 0, 5, 0)];
[ctView addStyle:title];
FTCoreTextStyle *bold = [FTCoreTextStyle styleWithName:#"bold"];
[bold setFont:[UIFont boldSystemFontOfSize:14]];
[ctView addStyle:bold];
FTCoreTextStyle *link = [FTCoreTextStyle styleWithName:FTCoreTextTagLink];
[link setColor:[UIColor blueColor]];
[ctView addStyle:link];
FTCoreTextStyle *bullets = [FTCoreTextStyle styleWithName:FTCoreTextTagBullet];
[bullets setBulletColor:kITCellFontColor];
[bullets setFont:kITItalicFont];
[bullets setParagraphInset:UIEdgeInsetsMake(0, 10, 0, 0)];
[ctView addStyle:bullets];
[ctView fitToSuggestedHeight];
[scrollView addSubview:ctView];
[scrollView setContentSize:[ctView suggestedSizeConstrainedToSize:CGSizeMake(scrollView.bounds.size.width, CGFLOAT_MAX)]];
//[ctView fitToSuggestedHeight];
//[ctView sizeToFit];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
CGRectMake(0, 0, 330, (self.view.bounds.size.height - 90))];
Replace 330 with 320. That should do the trick.
Edit: As written in the comments you should prefer self.view.bounds.size.width
The problem likely has to do with this line:
[scrollView setContentSize:[ctView suggestedSizeConstrainedToSize:CGSizeMake(scrollView.bounds.size.width, CGFLOAT_MAX)]];
I don't know what that method does, but it's probably giving you a contentSize with width > 320. Adding the following lines after that would fix it, I think:
if (scrollView.contentSize.width > self.view.bounds.size.width)
[scrollView setContentSize:CGSizeMake(self.view.bounds.size.width,scrollView.contentSize.height)];
I implemented an app Images in full screen are displayed fine.
After few seconds the navigation bar and status bar are hidden, now if i close the app and again open it, the navigation bar is displaced at the top of the screen where status bar overlaps on navigation bar
I guess i have to change something about the CGRect frame
Please help me
#import "KTPhotoScrollViewController.h"
#import "KTPhotoBrowserDataSource.h"
#import "KTPhotoBrowserGlobal.h"
#import "KTPhotoView.h"
const CGFloat ktkDefaultPortraitToolbarHeight = 44;
const CGFloat ktkDefaultLandscapeToolbarHeight = 33;
const CGFloat ktkDefaultToolbarHeight = 44;
#define BUTTON_DELETEPHOTO 0
#define BUTTON_CANCEL 1
#interface KTPhotoScrollViewController (KTPrivate)
- (void)setCurrentIndex:(NSInteger)newIndex;
- (void)toggleChrome:(BOOL)hide;
- (void)startChromeDisplayTimer;
- (void)cancelChromeDisplayTimer;
- (void)hideChrome;
- (void)showChrome;
- (void)swapCurrentAndNextPhotos;
- (void)nextPhoto;
- (void)previousPhoto;
- (void)toggleNavButtons;
- (CGRect)frameForPagingScrollView;
- (CGRect)frameForPageAtIndex:(NSUInteger)index;
- (void)loadPhoto:(NSInteger)index;
- (void)unloadPhoto:(NSInteger)index;
- (void)trashPhoto;
- (void)exportPhoto;
#end
#implementation KTPhotoScrollViewController
#synthesize statusBarStyle = statusBarStyle_;
#synthesize statusbarHidden = statusbarHidden_;
#synthesize my_img, imgURL;
- (void)dealloc
{
[nextButton_ release], nextButton_ = nil;
[previousButton_ release], previousButton_ = nil;
[scrollView_ release], scrollView_ = nil;
[toolbar_ release], toolbar_ = nil;
[photoViews_ release], photoViews_ = nil;
[dataSource_ release], dataSource_ = nil;
[super dealloc];
}
- (id)initWithDataSource:(id <KTPhotoBrowserDataSource>)dataSource andStartWithPhotoAtIndex:(NSUInteger)index
{
if (self = [super init]) {
startWithIndex_ = index;
dataSource_ = [dataSource retain];
// Make sure to set wantsFullScreenLayout or the photo
// will not display behind the status bar.
[self setWantsFullScreenLayout:YES];
BOOL isStatusbarHidden = [[UIApplication sharedApplication] isStatusBarHidden];
[self setStatusbarHidden:isStatusbarHidden];
self.hidesBottomBarWhenPushed = YES;
}
return self;
}
- (void)loadView
{
[super loadView];
CGRect scrollFrame = [self frameForPagingScrollView];
UIScrollView *newView = [[UIScrollView alloc] initWithFrame:scrollFrame];
[newView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
[newView setDelegate:self];
UIColor *backgroundColor = [dataSource_ respondsToSelector:#selector(imageBackgroundColor)] ?
[dataSource_ imageBackgroundColor] : [UIColor blackColor];
[newView setBackgroundColor:backgroundColor];
[newView setAutoresizesSubviews:YES];
[newView setPagingEnabled:YES];
[newView setShowsVerticalScrollIndicator:NO];
[newView setShowsHorizontalScrollIndicator:NO];
[[self view] addSubview:newView];
scrollView_ = [newView retain];
[newView release];
nextButton_ = [[UIBarButtonItem alloc]
initWithImage:[UIImage imageNamed:#"nextIcon.png"]
style:UIBarButtonItemStylePlain
target:self
action:#selector(nextPhoto)];
previousButton_ = [[UIBarButtonItem alloc]
initWithImage:[UIImage imageNamed:#"previousIcon.png"]
style:UIBarButtonItemStylePlain
target:self
action:#selector(previousPhoto)];
UIBarButtonItem *msgButton = nil;
UIBarButtonItem *exportButton = nil;
exportButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
target:self
action:#selector(exportPhoto)];
msgButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks
target:self
action:#selector(msgPhoto)];
// UIImage *image = [UIImage imageNamed:#"Icon-Small"];
// UIButton *myMuteButton = [UIButton buttonWithType:UIButtonTypeCustom];
// myMuteButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );
// [myMuteButton setImage:image forState:UIControlStateNormal];
// [myMuteButton addTarget:self action:#selector(trashPhoto) forControlEvents:UIControlEventTouchUpInside];
// UIBarButtonItem *myMuteBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myMuteButton];
UIBarItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSMutableArray *toolbarItems = [[NSMutableArray alloc] initWithCapacity:7];
if (exportButton) [toolbarItems addObject:exportButton];
[toolbarItems addObject:space];
[toolbarItems addObject:previousButton_];
[toolbarItems addObject:space];
[toolbarItems addObject:nextButton_];
[toolbarItems addObject:space];
if (msgButton) [toolbarItems addObject:msgButton];
// [toolbarItems addObject:myMuteBarButtonItem];
// [myMuteBarButtonItem release];
CGRect screenFrame = [[UIScreen mainScreen] bounds];
CGRect toolbarFrame = CGRectMake(0,
screenFrame.size.height - ktkDefaultToolbarHeight,
screenFrame.size.width,
ktkDefaultToolbarHeight);
toolbar_ = [[UIToolbar alloc] initWithFrame:toolbarFrame];
[toolbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin];
[toolbar_ setBarStyle:UIBarStyleBlackTranslucent];
[toolbar_ setItems:toolbarItems];
[[self view] addSubview:toolbar_];
if (msgButton) [msgButton release];
if (exportButton) [exportButton release];
[toolbarItems release];
[space release];
}
- (void) ShowAlert:(NSString*)title MyMsg:(NSString*)msg{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert autorelease];
}
- (void)setTitleWithCurrentPhotoIndex
{
NSString *formatString = NSLocalizedString(#"%1$i of %2$i", #"Picture X out of Y total.");
NSString *title = [NSString stringWithFormat:formatString, currentIndex_ + 1, photoCount_, nil];
[self setTitle:title];
}
- (void)scrollToIndex:(NSInteger)index
{
CGRect frame = scrollView_.frame;
frame.origin.x = frame.size.width * index;
frame.origin.y = 0;
[scrollView_ scrollRectToVisible:frame animated:NO];
}
- (void)setScrollViewContentSize
{
NSInteger pageCount = photoCount_;
if (pageCount == 0) {
pageCount = 1;
}
CGSize size = CGSizeMake(scrollView_.frame.size.width * pageCount,
scrollView_.frame.size.height / 2); // Cut in half to prevent horizontal scrolling.
[scrollView_ setContentSize:size];
}
- (void)viewDidLoad
{
[super viewDidLoad];
photoCount_ = [dataSource_ numberOfPhotos];
[self setScrollViewContentSize];
// Setup our photo view cache. We only keep 3 views in
// memory. NSNull is used as a placeholder for the other
// elements in the view cache array.
photoViews_ = [[NSMutableArray alloc] initWithCapacity:photoCount_];
for (int i=0; i < photoCount_; i++) {
[photoViews_ addObject:[NSNull null]];
}
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// The first time the view appears, store away the previous controller's values so we can reset on pop.
UINavigationBar *navbar = [[self navigationController] navigationBar];
if (!viewDidAppearOnce_) {
viewDidAppearOnce_ = YES;
navbarWasTranslucent_ = [navbar isTranslucent];
statusBarStyle_ = [[UIApplication sharedApplication] statusBarStyle];
}
// Then ensure translucency. Without it, the view will appear below rather than under it.
[navbar setTranslucent:YES];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];
// Set the scroll view's content size, auto-scroll to the stating photo,
// and setup the other display elements.
[self setScrollViewContentSize];
[self setCurrentIndex:startWithIndex_];
[self scrollToIndex:startWithIndex_];
[self setTitleWithCurrentPhotoIndex];
[self toggleNavButtons];
[self startChromeDisplayTimer];
}
- (void)viewWillDisappear:(BOOL)animated
{
// Reset nav bar translucency and status bar style to whatever it was before.
UINavigationBar *navbar = [[self navigationController] navigationBar];
[navbar setTranslucent:navbarWasTranslucent_];
[[UIApplication sharedApplication] setStatusBarStyle:statusBarStyle_ animated:YES];
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[self cancelChromeDisplayTimer];
[super viewDidDisappear:animated];
}
- (void)deleteCurrentPhoto
{
if (dataSource_) {
// TODO: Animate the deletion of the current photo.
NSInteger photoIndexToDelete = currentIndex_;
[self unloadPhoto:photoIndexToDelete];
[dataSource_ deleteImageAtIndex:photoIndexToDelete];
photoCount_ -= 1;
if (photoCount_ == 0) {
[self showChrome];
[[self navigationController] popViewControllerAnimated:YES];
} else {
NSInteger nextIndex = photoIndexToDelete;
if (nextIndex == photoCount_) {
nextIndex -= 1;
}
[self setCurrentIndex:nextIndex];
[self setScrollViewContentSize];
}
}
}
- (void)toggleNavButtons
{
[previousButton_ setEnabled:(currentIndex_ > 0)];
[nextButton_ setEnabled:(currentIndex_ < photoCount_ - 1)];
}
#pragma mark -
#pragma mark Frame calculations
#define PADDING 20
- (CGRect)frameForPagingScrollView
{
CGRect frame = [[UIScreen mainScreen] bounds];
frame.origin.x -= PADDING;
frame.size.width += (2 * PADDING);
return frame;
}
- (CGRect)frameForPageAtIndex:(NSUInteger)index
{
CGRect bounds = [scrollView_ bounds];
CGRect pageFrame = bounds;
pageFrame.size.width -= (2 * PADDING);
pageFrame.origin.x = (bounds.size.width * index) + PADDING;
return pageFrame;
}
#pragma mark -
#pragma mark Photo (Page) Management
- (void)loadPhoto:(NSInteger)index
{
if (index < 0 || index >= photoCount_) {
return;
}
id currentPhotoView = [photoViews_ objectAtIndex:index];
if (NO == [currentPhotoView isKindOfClass:[KTPhotoView class]]) {
// Load the photo view.
CGRect frame = [self frameForPageAtIndex:index];
KTPhotoView *photoView = [[KTPhotoView alloc] initWithFrame:frame];
[photoView setScroller:self];
[photoView setIndex:index];
[photoView setBackgroundColor:[UIColor clearColor]];
// Set the photo image.
if (dataSource_) {
if ([dataSource_ respondsToSelector:#selector(imageAtIndex:photoView:)] == NO) {
UIImage *image = [dataSource_ imageAtIndex:index];
[photoView setImage:image];
} else {
[dataSource_ imageAtIndex:index photoView:photoView];
}
}
[scrollView_ addSubview:photoView];
[photoViews_ replaceObjectAtIndex:index withObject:photoView];
[photoView release];
} else {
// Turn off zooming.
[currentPhotoView turnOffZoom];
}
}
- (void)unloadPhoto:(NSInteger)index
{
if (index < 0 || index >= photoCount_) {
return;
}
id currentPhotoView = [photoViews_ objectAtIndex:index];
if ([currentPhotoView isKindOfClass:[KTPhotoView class]]) {
[currentPhotoView removeFromSuperview];
[photoViews_ replaceObjectAtIndex:index withObject:[NSNull null]];
}
}
- (void)setCurrentIndex:(NSInteger)newIndex
{
currentIndex_ = newIndex;
if(newIndex>=0){
myUrl = [dataSource_ imageURLAtIndex:currentIndex_ photoView:[photoViews_ objectAtIndex:currentIndex_]];
myDescr = [dataSource_ imageDESCRAtIndex:currentIndex_ photoView:[photoViews_ objectAtIndex:currentIndex_]];
img_Title =[dataSource_ imageimg_TitleAtIndex:currentIndex_ photoView:[photoViews_ objectAtIndex:currentIndex_]];
}
[self loadPhoto:currentIndex_];
[self loadPhoto:currentIndex_ + 1];
[self loadPhoto:currentIndex_ - 1];
[self unloadPhoto:currentIndex_ + 2];
[self unloadPhoto:currentIndex_ - 2];
[self setTitleWithCurrentPhotoIndex];
[self toggleNavButtons];
}
#pragma mark -
#pragma mark Rotation Magic
- (void)updateToolbarWithOrientation:(UIInterfaceOrientation)interfaceOrientation
{
CGRect toolbarFrame = toolbar_.frame;
if ((interfaceOrientation) == UIInterfaceOrientationPortrait || (interfaceOrientation) == UIInterfaceOrientationPortraitUpsideDown) {
toolbarFrame.size.height = ktkDefaultPortraitToolbarHeight;
} else {
toolbarFrame.size.height = ktkDefaultLandscapeToolbarHeight+1;
}
toolbarFrame.size.width = self.view.frame.size.width;
toolbarFrame.origin.y = self.view.frame.size.height - toolbarFrame.size.height;
toolbar_.frame = toolbarFrame;
}
- (void)layoutScrollViewSubviews
{
[self setScrollViewContentSize];
NSArray *subviews = [scrollView_ subviews];
for (KTPhotoView *photoView in subviews) {
CGPoint restorePoint = [photoView pointToCenterAfterRotation];
CGFloat restoreScale = [photoView scaleToRestoreAfterRotation];
[photoView setFrame:[self frameForPageAtIndex:[photoView index]]];
[photoView setMaxMinZoomScalesForCurrentBounds];
[photoView restoreCenterPoint:restorePoint scale:restoreScale];
}
// adjust contentOffset to preserve page location based on values collected prior to location
CGFloat pageWidth = scrollView_.bounds.size.width;
CGFloat newOffset = (firstVisiblePageIndexBeforeRotation_ * pageWidth) + (percentScrolledIntoFirstVisiblePage_ * pageWidth);
scrollView_.contentOffset = CGPointMake(newOffset, 0);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
{
// here, our pagingScrollView bounds have not yet been updated for the new interface orientation. So this is a good
// place to calculate the content offset that we will need in the new orientation
CGFloat offset = scrollView_.contentOffset.x;
CGFloat pageWidth = scrollView_.bounds.size.width;
if (offset >= 0) {
firstVisiblePageIndexBeforeRotation_ = floorf(offset / pageWidth);
percentScrolledIntoFirstVisiblePage_ = (offset - (firstVisiblePageIndexBeforeRotation_ * pageWidth)) / pageWidth;
} else {
firstVisiblePageIndexBeforeRotation_ = 0;
percentScrolledIntoFirstVisiblePage_ = offset / pageWidth;
}
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
{
[self layoutScrollViewSubviews];
// Rotate the toolbar.
[self updateToolbarWithOrientation:toInterfaceOrientation];
// Adjust navigation bar if needed.
if (isChromeHidden_ && statusbarHidden_ == NO) {
UINavigationBar *navbar = [[self navigationController] navigationBar];
CGRect frame = [navbar frame];
frame.origin.y = 20;
[navbar setFrame:frame];
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self startChromeDisplayTimer];
}
- (UIView *)rotatingFooterView
{
return toolbar_;
}
#pragma mark -
#pragma mark Chrome Helpers
- (void)toggleChromeDisplay
{
[self toggleChrome:!isChromeHidden_];
}
- (void)toggleChrome:(BOOL)hide
{
isChromeHidden_ = hide;
if (hide) {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.4];
}
if ( ! [self isStatusbarHidden] ) {
if ([[UIApplication sharedApplication] respondsToSelector:#selector(setStatusBarHidden:withAnimation:)]) {
[[UIApplication sharedApplication] setStatusBarHidden:hide withAnimation:NO];
} else { // Deprecated in iOS 3.2+.
id sharedApp = [UIApplication sharedApplication]; // Get around deprecation warnings.
[sharedApp setStatusBarHidden:hide animated:NO];
}
}
CGFloat alpha = hide ? 0.0 : 1.0;
// Must set the navigation bar's alpha, otherwise the photo
// view will be pushed until the navigation bar.
UINavigationBar *navbar = [[self navigationController] navigationBar];
[navbar setAlpha:alpha];
[toolbar_ setAlpha:alpha];
if (hide) {
[UIView commitAnimations];
}
if ( ! isChromeHidden_ ) {
[self startChromeDisplayTimer];
}
}
- (void)hideChrome
{
if (chromeHideTimer_ && [chromeHideTimer_ isValid]) {
[chromeHideTimer_ invalidate];
chromeHideTimer_ = nil;
}
[self toggleChrome:YES];
}
- (void)showChrome
{
[self toggleChrome:NO];
}
- (void)startChromeDisplayTimer
{
[self cancelChromeDisplayTimer];
chromeHideTimer_ = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(hideChrome)
userInfo:nil
repeats:NO];
}
- (void)cancelChromeDisplayTimer
{
if (chromeHideTimer_) {
[chromeHideTimer_ invalidate];
chromeHideTimer_ = nil;
}
}
#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat pageWidth = scrollView.frame.size.width;
float fractionalPage = scrollView.contentOffset.x / pageWidth;
NSInteger page = floor(fractionalPage);
if (page != currentIndex_) {
[self setCurrentIndex:page];
}
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self hideChrome];
}
#pragma mark -
#pragma mark Toolbar Actions
- (void)nextPhoto
{
[self scrollToIndex:currentIndex_ + 1];
[self startChromeDisplayTimer];
}
- (void)previousPhoto
{
[self scrollToIndex:currentIndex_ - 1];
[self startChromeDisplayTimer];
}
- (void)msgPhoto
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:img_Title message:myDescr delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
NSString *message;
NSString *title;
if (!error) {
title = #"Done";
message = #"image copied to your local gallery";
} else {
title = #"Error";
message = [error description];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
//save to gallery
UIImage *imageB = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: myUrl]]];
UIImageWriteToSavedPhotosAlbum(imageB, self, #selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), nil);
} else if (buttonIndex == 1) {
//email
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
mailComposer.toolbar.barStyle = UIBarStyleBlack;
mailComposer.title = #"Your title here";
[[mailComposer navigationBar] setTintColor:[UIColor colorWithRed:124.0/255 green:17.0/255 blue:92.0/255 alpha:1]];
if ([MFMailComposeViewController canSendMail]) {
[mailComposer setSubject:#"Look at a great image"];
[mailComposer setMessageBody:[NSString stringWithFormat:#"%#",myUrl] isHTML:NO];
UIImage *imageB = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: myUrl]]];
NSData *exportData = UIImageJPEGRepresentation(imageB ,1.0);
[mailComposer addAttachmentData:exportData mimeType:#"image/jpeg" fileName:img_Title];
[self presentModalViewController:mailComposer animated:YES];
}
//release the mailComposer as it is now being managed as the UIViewControllers modalViewController.
[mailComposer release];
} else if (buttonIndex == 2) {
//cancel
}
[self startChromeDisplayTimer];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissModalViewControllerAnimated:YES];
if (result == MFMailComposeResultFailed) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to send message" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
- (void) exportPhoto
{
if ([dataSource_ respondsToSelector:#selector(exportImageAtIndex:)])
[dataSource_ exportImageAtIndex:currentIndex_];
[self startChromeDisplayTimer];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Actions"
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Save to gallery", #"Email",nil];
[actionSheet showInView:[self view]];
[actionSheet release];
}
#end
First of all, tel me if you want to show Status Bar or not.
If you dont want to show then, in nib of controller's, you can select its view, and under its properties set StatusBar to NONE, thar time it wont show status bar... and you can set vew size to (320*480) or else with status bar it will be (320*460) and 20 pixels will be reserved for status bar.
Other ways to do (without using above method)
Can hide StatusBar from info.plist also, by setting property UIStatusBarHidden property to YES. (To hide the status bar when the app launches)
Programmatically can be done, add line to appDelegate's applicationDidFinishLaunching method,
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
I have a page controller and that method pageAction defined like this :
-(void)pageAction:(UIPageControl*)control
{
NSLog(#"page changed");
[self getVehicules];
[self.tableViewVehiculesPossedes release];
int page = pageControlVehiculePossedee.currentPage;
NSLog(#"page %d", page);
[self loadScrollViewWithPage:page];
CGRect frame = pageControlVehiculePossedee.frame;
frame.origin.x = (vosvehiculeScrollView.frame.size.width * page);
[vosvehiculeScrollView scrollRectToVisible:frame animated:YES];
pageControlUsed = YES;
}
Every time I change the page I need to display a tableview with some labels. Here is the code :
- (void)viewDidLoad
{
[super viewDidLoad];
[self getVehicules];
vosvehiculeScrollView.pagingEnabled = YES;
vosvehiculeScrollView.showsHorizontalScrollIndicator = NO;
vosvehiculeScrollView.showsVerticalScrollIndicator = NO;
vosvehiculeScrollView.scrollsToTop = NO;
pageControlVehiculePossedee.numberOfPages=[vehiculesPossede count];
pageControlVehiculePossedee.currentPage=0;
[self loadScrollViewWithPage:0];
[pageControlVehiculePossedee addTarget:self action:#selector(pageAction:) forControlEvents:UIControlEventValueChanged];
votreVehiculeLabel.text=#"Votre véhicule";
vehiculesPossedesArray = [[NSMutableArray alloc] initWithObjects:#"Annee modele", #"Transmission",#"Carburant", nil];
}
- (void) loadScrollViewWithPage: (int) page {
if (page < 0) return;
if (page >= [vehiculesPossede count]) return;
tableViewVehiculesPossedes=[[UITableView alloc] initWithFrame:CGRectMake(3, 80, 315, 171) style:UITableViewStyleGrouped];
tableViewVehiculesPossedes.tag=page;
tableViewVehiculesPossedes.bounces=NO;
tableViewVehiculesPossedes.backgroundColor=[UIColor clearColor];
[tableViewVehiculesPossedes setDelegate:self];
[tableViewVehiculesPossedes setDataSource:self];
[self.vosvehiculeScrollView addSubview:tableViewVehiculesPossedes];
nameVehiculeLabel.text=[[vehiculesPossede objectAtIndex:page] valueForKey:#"modele"];
self.transmissionString=[[vehiculesPossede objectAtIndex:page]valueForKey:#"transmision"];
self.carburantString=[[vehiculesPossede objectAtIndex:page] valueForKey:#"carburant"];
self.anneeModelString=[[vehiculesPossede objectAtIndex:page] valueForKey:#"modele_annee"];
self.anneeString=[[vehiculesPossede objectAtIndex:page]valueForKey:#"annee"];
if(page==0){
NSLog(#"0");
self.transmissionString=#"ttt";
}
else NSLog(#"1");
}
The problem is that even I put [self.tableViewVehiculesPossedes release]; on the change page method, the tableView appear overlay and the text from labels are overlay. What can I do with the tableview to make it dissapear when a new page will be display?
Please help me..I spent a lot of time with this :|
If I get it correctly I think you should keep an ivar to the table you create with the alloc in loadScrollViewWithPage, and when switching page you should removing it from the view by calling :
[mytableview removeFromSuperview];
And most likely your should take care of releasing it as well as I can't see it in your code.
My page control only shows on the first page of the UIScrollView. Once I scroll to the next page it disappears.
Could you tell me what I'm doing wrong? Because I'm curious as to whether I need to add a subview of the page control each time I add a subview to my UIScrollView.
My relevant pieces of code:
-(IBAction)clickPageControl:(id)sender
{
int page=pageControl.currentPage;
CGRect frame=scroller.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scroller scrollRectToVisible:frame animated:YES];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int page = scrollView.contentOffset.x/scrollView.frame.size.width;
pageControl.currentPage=page;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
arrayCount = [array count];
scroller.delegate=self;
scroller.pagingEnabled=YES;
scroller.directionalLockEnabled=YES;
scroller.showsHorizontalScrollIndicator=NO;
scroller.showsVerticalScrollIndicator=NO;
//should have an array of photo objects and the number of objects, correct?
scrollWidth = 0;
scroller.contentSize=CGSizeMake(arrayCount*scroller.frame.size.width, scroller.frame.size.height);
for (int i = 0; i < arrayCount;i++) {
PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:#"PhotoViewController" bundle:nil];
UIImageView *scrollImageView = [[UIImageView alloc] initWithFrame:CGRectOffset(scroller.bounds, scrollWidth, 0)];
CGRect rect = scrollImageView.frame;
pvc.view.frame = rect;
[pvc view];
pvc.label.textColor = [UIColor whiteColor];
id individualPhoto = [array objectAtIndex:i];
NSLog(#"%#",individualPhoto);
NSArray *keys=[individualPhoto allKeys];
NSLog(#"%#",keys);
NSString *imageURL=[individualPhoto objectForKey:#"source"];
//here you can use this imageURL to get image-data and display it in imageView
NSURL *url = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
pvc.imageView.image = [[UIImage alloc] initWithData:data];
pvc.label.text = [NSString stringWithFormat:#"Photo Number: %i", arrayCount];
//check to make sure the proper URL was passed
//I have an imageView next to the UIScrollView to test whether that works - it does.
[scroller addSubview:pvc.view];
[scrollImageView release];
[pvc release];
scrollWidth += scroller.frame.size.width;
}
if (arrayCount > 3) {
pageControl.numberOfPages=3;
} else {
pageControl.numberOfPages=arrayCount;
}
pageControl.currentPage=0;
[self.view addSubview:scroller];
}
You should not add your page control as a subview of the scroll view, this causes it to scroll with the content. Make it a sibling of the scroll view instead.
I have a view on which I can draw. When the user clicks on cancel button, the view is cleared and new Image is drawn in that view. I am posting my code. Can anyone help?
#import "SignatureViewController.h"
#implementation SignatureViewController
#synthesize salesToolBar;
-(void)buttonpressed
{
NSString *allElements = [myarray componentsJoinedByString:#""];
NSLog(#"%#", allElements);}
-(void)buttonclear{
[drawImage removeFromSuperview];
//UIGraphicsBeginImageContext(CGSizeMake(self.view.frame.size.height, self.view.frame.size.width));
drawImage = [[UIImageView alloc] initWithImage:nil];
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width )];
drawImage.frame = self.view.frame;
[self.view addSubview:drawImage];
self.view.backgroundColor = [UIColor greenColor];
mouseMoved = 0;
//[super viewDidLoad];
}
-(void)buttoncancel{
[[self navigationController] popViewControllerAnimated: YES];
[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait;
}
- (void)viewDidLoad {
[super viewDidLoad];
myarray = [[NSMutableArray alloc] init];
CGFloat x = self.view.bounds.size.width / 2.0;
CGFloat y = self.view.bounds.size.height / 2.0;
CGPoint center = CGPointMake(y, x);
// set the new center point
self.view.center = center;
CGAffineTransform transform = self.view.transform;
transform = CGAffineTransformRotate(transform, -(M_PI / 2.0));
self.view.transform = transform;
self.view.backgroundColor = [UIColor greenColor];
self.title = #"Signature";
[self createToolbar];
NSLog(#"View Did Load Run");
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"Self.view.frame.height = %f and width = %f ", self.view.frame.size.height, self.view.frame.size.width);
NSLog(#"View Did Appear Run");
self.navigationController.navigationBarHidden=TRUE;
[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeLeft;
[super viewDidLoad];
}
Sounds like you need to call setNeedsDisplay: on the view. :)