tableView:didSelectRowAtIndexPath not firing after swipe gesture is called - iphone

This is a localized issue. I'm going to post a lot of code, and provide a lot of explanation. Hopefully... someone can help me with this.
In my application I have a "Facebook-style" menu. The iOS Facebook app, to be more specific. You can access this menu in two different ways. You may either touch the menu button, or swipe to open the menu. When one opens and closes the menu using the button, the tableView:didSelectRowAtIndexPath method fires perfectly upon touching the cell. When one opens and closes the menu using the swipe method... it does not. You have to touch the table cell twice for the method to fire. The code for these methods are exactly the same in several classes, however, this is the only one I have an issue with. Take a look; see if I'm dropping the ball somewhere:
#import "BrowseViewController.h"
#implementation BrowseViewController
#synthesize browseView, table, countriesArray, btnSideHome, btnSideBrowse, btnSideFave, btnSideNew, btnSideCall, btnSideBeset, btnSideEmail, btnSideCancelled, menuOpen, navBarTitle, mainSearchBar, tap;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.font = [UIFont fontWithName:#"STHeitiSC-Medium" size:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:1.0];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
label.text = #"Countries";
self.navBarTitle.titleView = label;
[label sizeToFit];
CheckNetworkStatus *networkCheck = [[CheckNetworkStatus alloc] init];
BOOL internetActive = [networkCheck checkNetwork];
if (internetActive) {
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
tap.delegate = self;
tap.cancelsTouchesInView = NO;
UISwipeGestureRecognizer *oneFingerSwipeLeft =
[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeLeft:)];
[oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[[self view] addGestureRecognizer:oneFingerSwipeLeft];
UISwipeGestureRecognizer *oneFingerSwipeRight =
[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeRight:)];
[oneFingerSwipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
[[self view] addGestureRecognizer:oneFingerSwipeRight];
menuOpen = NO;
table.userInteractionEnabled = YES;
NSArray *countries = [[NSArray alloc] initWithObjects:#"United States", #"Canada", #"Mexico", nil];
self.countriesArray = countries;
} else {
//No interwebz, notify user and send them to the home page
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Connection Error" message:#"Failed to connect to the server. Please verify that you have an active internet connection and try again. If the problem persists, please call us at **********" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[message show];
PassportAmericaViewController *homeView = [[PassportAmericaViewController alloc]
initWithNibName:#"PassportAmericaViewController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:homeView animated:YES];
}
[super viewDidLoad];
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection: (NSInteger)section
{
return [countriesArray count];
NSLog(#"Number of objecits in countriesArray: %i", [countriesArray count]);
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.font = [UIFont fontWithName:#"STHeitiSC-Medium" size:20.0];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [countriesArray objectAtIndex:row];
return cell;
}
- (void)tableView:(UITableView *)table
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *countrySelected = [countriesArray objectAtIndex:indexPath.row];
Campground *_Campground = [[Campground alloc] init];
_Campground.country = countrySelected;
StateViewController *stateView = [[StateViewController alloc]
initWithNibName:#"StateView" bundle:[NSBundle mainBundle]];
stateView._Campground = _Campground;
[self.navigationController pushViewController:stateView animated:YES];
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(void) dismissKeyboard {
[mainSearchBar resignFirstResponder];
}
-(IBAction)goBack:(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if ([animationID isEqualToString:#"slideMenu"]){
UIView *sq = (__bridge UIView *) context;
[sq removeFromSuperview];
}
}
- (IBAction)menuTapped {
NSLog(#"Menu tapped");
CGRect frame = self.browseView.frame;
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector( animationDidStop:finished:context: )];
[UIView beginAnimations:#"slideMenu" context:(__bridge void *)(self.browseView)];
if(!menuOpen) {
frame.origin.x = -212;
menuOpen = YES;
table.userInteractionEnabled = NO;
}
else
{
frame.origin.x = 0;
menuOpen = NO;
table.userInteractionEnabled = YES;
}
self.browseView.frame = frame;
[UIView commitAnimations];
}
-(IBAction) sideHome:(id)sender{
CGRect frame = self.browseView.frame;
frame.origin.x = 0;
self.browseView.frame = frame;
menuOpen = NO;
PassportAmericaViewController *homeView = [[PassportAmericaViewController alloc]
initWithNibName:#"PassportAmericaViewController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:homeView animated:YES];
table.userInteractionEnabled = YES;
}
-(IBAction) sideBrowse:(id)sender{
CGRect frame = self.browseView.frame;
frame.origin.x = 0;
self.browseView.frame = frame;
menuOpen = NO;
BrowseViewController *browseView2 = [[BrowseViewController alloc]
initWithNibName:#"BrowseView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:browseView2 animated:YES];
table.userInteractionEnabled = YES;
}
-(IBAction) sideBeset:(id)sender{
CGRect frame = self.browseView.frame;
frame.origin.x = 0;
self.browseView.frame = frame;
menuOpen = NO;
BesetCampgroundMapViewController *besetMapView = [[BesetCampgroundMapViewController alloc]
initWithNibName:#"BesetCampgroundMapView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:besetMapView animated:YES];
table.userInteractionEnabled = YES;
}
-(IBAction) sideFave:(id)sender{
CGRect frame = self.browseView.frame;
frame.origin.x = 0;
self.browseView.frame = frame;
menuOpen = NO;
FavoritesViewController *faveView = [[FavoritesViewController alloc] initWithNibName:#"FavoritesView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:faveView animated:YES];
table.userInteractionEnabled = YES;
}
-(IBAction) sideNew:(id)sender{
CGRect frame = self.browseView.frame;
frame.origin.x = 0;
self.browseView.frame = frame;
menuOpen = NO;
NewCampgroundsViewController *theNewCampView = [[NewCampgroundsViewController alloc]
initWithNibName:#"NewCampgroundsView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:theNewCampView animated:YES];
table.userInteractionEnabled = YES;
}
-(IBAction) sideCancelled:(id)sender{
CGRect frame = self.browseView.frame;
frame.origin.x = 0;
self.browseView.frame = frame;
menuOpen = NO;
CancelledCampgroundsViewController *cancCampView = [[CancelledCampgroundsViewController alloc]
initWithNibName:#"CancelledCampgroundsView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:cancCampView animated:YES];
table.userInteractionEnabled = YES;
}
-(IBAction) sideCall:(id)sender{
NSLog(#"Calling Passport America...");
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"tel:**********"]];
table.userInteractionEnabled = YES;
}
-(IBAction) sideEmail:(id)sender{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: #"mailto:***************"]];
table.userInteractionEnabled = YES;
}
-(void) searchBarSearchButtonClicked: (UISearchBar *)searchBar {
SearchViewController *search = [[SearchViewController alloc] initWithNibName:#"SearchViewController" bundle:[NSBundle mainBundle]];
NSString *searchText = [[NSString alloc] initWithString:mainSearchBar.text];
search.searchText = searchText;
[self dismissKeyboard];
[self.navigationController pushViewController:search animated:YES];
table.userInteractionEnabled = YES;
menuOpen = NO;
CGRect frame = self.browseView.frame;
frame.origin.x = 0;
self.browseView.frame = frame;
}
-(void) swipeLeft:(UISwipeGestureRecognizer *)recognizer {
if (!menuOpen) {
CGRect frame = self.browseView.frame;
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector( animationDidStop:finished:context: )];
[UIView beginAnimations:#"slideMenu" context:(__bridge void *)(self.browseView)];
frame.origin.x = -212;
menuOpen = YES;
self.browseView.frame = frame;
table.userInteractionEnabled = NO;
[UIView commitAnimations];
} else {
//menu already open, do nothing
}
}
-(void) swipeRight:(UISwipeGestureRecognizer *)recognizer {
if (!menuOpen) {
//menu closed, do nothing
} else {
CGRect frame = self.browseView.frame;
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector( animationDidStop:finished:context: )];
[UIView beginAnimations:#"slideMenu" context:(__bridge void *)(self.browseView)];
frame.origin.x = 0;
menuOpen = NO;
self.browseView.frame = frame;
table.userInteractionEnabled = YES;
[UIView commitAnimations];
}
}
- (void) viewWillDisappear:(BOOL)animated {
[self.table deselectRowAtIndexPath:[self.table indexPathForSelectedRow] animated:animated];
[super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning {
NSLog(#"Memory Warning!");
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
self.table = nil;
self.countriesArray = nil;
self.browseView = nil;
[super viewDidUnload];
}
#end

Determine which cell the swipe takes place in, compute the index path, and call didSelectRowAtIndexPath from your gestureRecognizer code.

Related

iOS and Objective-C: why does my UIWebView gets fullscreen when I click a link on it?

At first, sorry for my bad English, I'm just learning it. Im relatively new at Objective-C and I'm using FBConnect bundle to link my app to Facebook. All it's working correctly, but when I click a link into the UIWebView (the Facebook login button, for example), my UIWebView gets fullscreen and hides my close button (a little 'x' button in the top right of the UIWebView, called here "_closeButton").
Here's the code:
The "init" method:
- (id)init {
if ((self = [super initWithFrame:CGRectZero])) {
_delegate = nil;
_loadingURL = nil;
_showingKeyboard = NO;
self.backgroundColor = [UIColor clearColor];
self.autoresizesSubviews = NO;
//self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.contentMode = UIViewContentModeRedraw;
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(kPadding, kPadding, 480, 480)];
_webView.delegate = self;
//_webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:_webView];
//UIImage* closeImage = [UIImage imageNamed:#"FBDialog.bundle/images/close.png"];
UIImage* closeImage = [UIImage imageNamed:#"close"];
UIColor* color = [UIColor colorWithRed:255.0/255 green:/*184.0*/0.0/255 blue:/*216.0*/0.0/255 alpha:1];
_closeButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
[_closeButton setImage:closeImage forState:UIControlStateNormal];
[_closeButton setTitleColor:color forState:UIControlStateNormal];
[_closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[_closeButton addTarget:self action:#selector(cancel)
forControlEvents:UIControlEventTouchUpInside];
// To be compatible with OS 2.x
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_2_2
_closeButton.font = [UIFont boldSystemFontOfSize:12];
#else
_closeButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
#endif
_closeButton.showsTouchWhenHighlighted = YES;
_closeButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin
| UIViewAutoresizingFlexibleBottomMargin;
[self addSubview:_closeButton];
NSLog(#"close");
_spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
UIActivityIndicatorViewStyleWhiteLarge];
_spinner.autoresizingMask =
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
| UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self addSubview:_spinner];
_modalBackgroundView = [[UIView alloc] init];
}
return self;
}
The delegate of the WebView (I suspect here's where I need to do the trick)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSURL* url = request.URL;
if ([url.scheme isEqualToString:#"fbconnect"]) {
if ([[url.resourceSpecifier substringToIndex:8] isEqualToString:#"//cancel"]) {
NSString * errorCode = [self getStringFromUrl:[url absoluteString] needle:#"error_code="];
NSString * errorStr = [self getStringFromUrl:[url absoluteString] needle:#"error_msg="];
if (errorCode) {
NSDictionary * errorData = [NSDictionary dictionaryWithObject:errorStr forKey:#"error_msg"];
NSError * error = [NSError errorWithDomain:#"facebookErrDomain"
code:[errorCode intValue]
userInfo:errorData];
[self dismissWithError:error animated:YES];
} else {
[self dialogDidCancel:url];
}
} else {
[self dialogDidSucceed:url];
}
return NO;
} else if ([_loadingURL isEqual:url]) {
return YES;
} else if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([_delegate respondsToSelector:#selector(dialog:shouldOpenURLInExternalBrowser:)]) {
if (![_delegate dialog:self shouldOpenURLInExternalBrowser:url]) {
return NO;
}
}
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
} else {
return YES;
}
}
And the show method (called when I need to show the Web View)
- (void)show {
NSLog(#"Cuantas veces me ves?");
[self load];
[self sizeToFitOrientation:NO];
CGFloat innerWidth = self.frame.size.width - (kBorderWidth+1)*2;
[_closeButton sizeToFit];
_closeButton.frame = CGRectMake(
2,
2,
29,
29);
_webView.frame = CGRectMake(
kBorderWidth+1,
kBorderWidth+1,
innerWidth,
self.frame.size.height - (1 + kBorderWidth*2));
[_spinner sizeToFit];
[_spinner startAnimating];
_spinner.center = _webView.center;
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
_modalBackgroundView.frame = window.frame;
[_modalBackgroundView addSubview:self];
[window addSubview:_modalBackgroundView];
[window addSubview:self];
[self dialogWillAppear];
self.transform = CGAffineTransformScale([self transformForOrientation], 0.001, 0.001);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration/1.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(bounce1AnimationStopped)];
self.transform = CGAffineTransformScale([self transformForOrientation], 1.1, 1.1);
[UIView commitAnimations];
[self addObservers];
}
Googling the problem, I found that this could be the Default behaviour of the UIWebView. How can I change it to make all my WebViews of the same size than the first one?
Thanks in advance!
== EDIT ==
Still don't know why is my UIWebView acting like this, or how to solve it, but since the code is part of the FBConnect Bundle, I suppose I shouldn't edit it too much. I just created programmatically a new close button on the top and that's all. But I'll let the question open if someone knows how to solve it. Thanks to Leo Natan for his help.

How to hide/Remove the search bar on Contact Picker

I am adding a contact picker in my app, however, I do not want the search functionality.
How to hide/Remove the search bar on Contact Picker (ABPeoplePickerNavigationController)?
static BOOL foundSearchBar = NO;
- (void)findSearchBar:(UIView*)parent mark:(NSString*)mark {
for( UIView* v in [parent subviews] ) {
//if( foundSearchBar ) return;
NSLog(#"%#%#",mark,NSStringFromClass([v class]));
if( [v isKindOfClass:[UISearchBar class]] ) {
[(UISearchBar*)v setTintColor:[UIColor blackColor]];
v.hidden=YES;
// foundSearchBar = YES;
break;
}
if( [v isKindOfClass:[UITableView class]] ) {
CGRect temp =v.frame;
temp.origin.y=temp.origin.y-44;
temp.size.height=temp.size.height+44;
v.frame=temp;
//foundSearchBar = YES;
break;
}
[self findSearchBar:v mark:[mark stringByAppendingString:#"> "]];
}
}
call above method after picker is presented as below:
-(void)showPeoplePickerController
{
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
picker.view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
// Display only a person's phone, email, and birthdate
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],
[NSNumber numberWithInt:kABPersonEmailProperty],
[NSNumber numberWithInt:kABPersonBirthdayProperty],[NSNumber numberWithInt:kABPersonAddressProperty],nil];
picker.displayedProperties = displayedItems;
// Show the picker
[self presentViewController:picker animated:YES completion:nil];
[self findSearchBar:[picker view] mark:#"> "];
[picker release];
}
-(void)showAddressBook {
ABPeoplePickerNavigationController *addressBook = [[ABPeoplePickerNavigationController alloc] init];
[addressBook setPeoplePickerDelegate:self];
addressBook.delegate = self;
addressBook.navigationBar.topItem.title = #"iPhone Contacts";
UIView *view = addressBook.topViewController.view;
for (UIView *v in view.subviews) {
if ( [v isKindOfClass:[UITableView class]] ) {
CGRect temp = v.frame;
temp.origin.y = temp.origin.y - 44;
temp.size.height = temp.size.height + 44;
v.frame = temp;
}
}
[addressBook release];
}
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
if ([navigationController isKindOfClass:[ABPeoplePickerNavigationController class]]) {
UISearchDisplayController *searchDisplayController = navigationController.topViewController.searchDisplayController;
[searchDisplayController.searchBar setHidden:YES];
}
}

When Im moving view picked from cloudScrollView not showing the picked view in front

Adding UIImageView on UIScrollView and adding UIPanGestureRecognizer to it
UIImageView* lbl = [[UIImageView alloc]init];
NSString* tempStr = [NSString stringWithFormat:#"images/%#",[self.cloudArray objectAtIndex:i]];
NSString* imgPath = [self appendDocumentDirectoryPath:tempStr];
lbl.image = [[[UIImage alloc] initWithContentsOfFile:imgPath] autorelease];
[lbl setUserInteractionEnabled:YES];
//add gestures
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(moveImage:)];
[panGesture setMinimumNumberOfTouches:1];
[panGesture setMaximumNumberOfTouches:1];
[lbl addGestureRecognizer:panGesture];
[panGesture release];
CGSize expectedLabelSize = CGSizeMake(150, height);
lbl.frame = CGRectMake(pntX, pntY, expectedLabelSize.width, height);
[rectFrame addObject:[NSValue valueWithCGRect:lbl.frame]];
lbl.tag = i;
[cloudScrollView addSubview:lbl];
[lbl release];
lbl = nil;
pntX = pntX + space + expectedLabelSize.width;
[cloudScrollView setContentSize:CGSizeMake([cloudArray count]*170, 160)];
#pragma mark METHOD TO CATCH MOVE GESTURE EVENTS
- (void)moveImage:(UIPanGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateChanged) {
location1 = [gesture locationInView:cloudScrollView];
view1 = [gesture view];
if (isFirstTime) {
isFirstTime = NO;
draggedTag = view1.tag;
}
[view1 setCenter:CGPointMake(location1.x, location1.y)];
}
if (gesture.state == UIGestureRecognizerStateEnded) {
CGPoint pnt = [gesture locationInView:customTableView];
NSIndexPath* indexPath = [customTableView indexPathForRowAtPoint:pnt];
NSLog(#"indexpath = %d",indexPath.row);
if (index >= 0) {
[self.ansArray replaceObjectAtIndex:indexPath.row withObject:[self.cloudArray objectAtIndex:draggedTag]];//[self.cloudArray objectAtIndex:draggedTag]
[customTableView reloadData];
}
CGRect draggedItemRect = [[rectFrame objectAtIndex:draggedTag] CGRectValue];
view1.frame = draggedItemRect;
isFirstTime = YES;
}
}

How to delete label that created programmatically?

I am creating two label programmatically using this code..
-(void)addLabel:(id)sender
{
ExampleAppDataObject* theDataObject = [self theAppDataObject];
theDataObject.count = theDataObject.count+1;
NSLog(#"count is :%i",theDataObject.count);
if (theDataObject.count == 2) {
addLabel.enabled = NO;
}
if (theDataObject.count == 1) {
CGRect imageFrame = CGRectMake(10, 10, 150, 80);
labelResizableView = [[UserResizableView alloc] initWithFrame:imageFrame];
blabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 100, 100)];
blabel.text = #"Write here";
//alabel.text = self.newsAsset.title;
blabel.adjustsFontSizeToFitWidth = NO;
blabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
blabel.font = [UIFont boldSystemFontOfSize:18.0];
blabel.textColor = [UIColor blueColor];
// alabel.shadowColor = [UIColor whiteColor];
// alabel.shadowOffset = CGSizeMake(0, 1);
blabel.backgroundColor = [UIColor clearColor];
blabel.lineBreakMode = UILineBreakModeWordWrap;
blabel.numberOfLines = 10;
blabel.minimumFontSize = 8.;
blabel.adjustsFontSizeToFitWidth = YES;
[blabel sizeToFit];
labelResizableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// enable touch delivery
blabel.userInteractionEnabled = YES;
//tao gasture recognizer for label
UITapGestureRecognizer *doubleTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(blabelTap:)];
doubleTap.numberOfTapsRequired = 2;
[blabel addGestureRecognizer:doubleTap];
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:#selector(longPress:)];
[longPressGesture setMinimumPressDuration:1];
[blabel addGestureRecognizer:longPressGesture];
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [greetString sizeWithFont:blabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:blabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = blabel.frame;
newFrame.size.height = expectedLabelSize.height+40;
newFrame.size.width = expectedLabelSize.width+40;
blabel.frame = newFrame;
labelResizableView.frame = newFrame;
labelResizableView.contentView = blabel;
labelResizableView.delegate = self;
labelResizableView.tag =2;
[self.view addSubview:labelResizableView];
}else if (theDataObject.count == 2) {
CGRect imageFrame = CGRectMake(10, 10, 150, 80);
labelResizableView = [[UserResizableView alloc] initWithFrame:imageFrame];
clabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 35, 100, 100)];
clabel.text = #"Write here";
//alabel.text = self.newsAsset.title;
clabel.adjustsFontSizeToFitWidth = NO;
clabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
clabel.font = [UIFont boldSystemFontOfSize:18.0];
clabel.textColor = [UIColor blueColor];
// alabel.shadowColor = [UIColor whiteColor];
// alabel.shadowOffset = CGSizeMake(0, 1);
clabel.backgroundColor = [UIColor clearColor];
clabel.lineBreakMode = UILineBreakModeWordWrap;
clabel.numberOfLines = 10;
clabel.minimumFontSize = 8.;
clabel.adjustsFontSizeToFitWidth = YES;
[clabel sizeToFit];
labelResizableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// enable touch delivery
clabel.userInteractionEnabled = YES;
//tao gasture recognizer for label
UITapGestureRecognizer *doubleTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(clabelTap:)];
doubleTap.numberOfTapsRequired = 2;
[clabel addGestureRecognizer:doubleTap];
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:#selector(longPress:)];
[longPressGesture setMinimumPressDuration:1];
[clabel addGestureRecognizer:longPressGesture];
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [greetString sizeWithFont:clabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:clabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = blabel.frame;
newFrame.size.height = expectedLabelSize.height+40;
newFrame.size.width = expectedLabelSize.width+40;
clabel.frame = newFrame;
labelResizableView.frame = newFrame;
labelResizableView.contentView = clabel;
labelResizableView.delegate = self;
labelResizableView.tag=3;
[self.view addSubview:labelResizableView];
}
}
And when user long press button than it will be deleted...
- (void)longPress:(UILongPressGestureRecognizer *)longPressGesture {
if (longPressGesture.state == UIGestureRecognizerStateEnded) {
//NSLog(#"Long press Ended");
// NSLog(#"blabel long pressed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Delete Label" message:#"Want delete label" delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes",nil];
[alert show];
}
else {
//NSLog(#"Long press detected.");
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
ExampleAppDataObject* theDataObject = [self theAppDataObject];
if (theDataObject.count!=0) {
theDataObject.count = theDataObject.count-1;
}
addLabel.enabled = YES;
[labelResizableView removeFromSuperview];
// NSLog(#"yes btn tapped");
}
}
but now when i longpree blabel than still clabel is deleted and it will never delete blabel.thanx in advance.
Use the Tag property to remove the labelResizableView.
-(void)addLabel:(id)sender
{
labelResizableView = [[UserResizableView alloc] initWithFrame:imageFrame];
labelResizableView.tag = 100;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
ExampleAppDataObject* theDataObject = [self theAppDataObject];
if (theDataObject.count!=0) {
theDataObject.count = theDataObject.count-1;
}
addLabel.enabled = YES;
UILabel *tempLabel = (UILabel *)[self.view viewWithTag:100];
if(tempLabel)
[tempLabel removeFromSuperview];
}
}
hope this code help you :)
NSArray *subArray = [self.view subviews];
if([subArray count] != 0) {
for(int i = 0 ; i < [subArray count] ; i++) {
[[subArray objectAtIndex:i] removeFromSuperview];
}
}
To add control in your view:
[self.view addsubview:yourcontrolid];
ex:
[self.view addsubview:labelid];
To add control from your view:
[controlid removefromsuperview];
ex
[labelid removefromsuperview];
you are adding with :
[self.view addSubview:labelResizableView];
than remove it the labelResizableView, and release the clabel or blabel, whatever is in your case.
Maybe this gives an example
It is because your code
else if (theDataObject.count == 2) {
is calling and in this code you are adding
labelResizableView.contentView = clabel;
and then you are adding this to you view
[self.view addSubview:labelResizableView];
So when you are deleting labelResizableView
[labelResizableView removeFromSuperview];
So the result is you are adding labelResizableView 2 times and remove the labelResizableView which have clabel.

iphone FullScreen navigation bar displacement

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