Implement Simple Payment Using PayPal in iPhone Application? - iphone

I am trying to implement Making a Simple Payment through PayPal in IOS Application. I tried the PayPal API. The Sample code given By API is working fine. I am trying to implement in my application it wont getting correctly it getting crash . Is there any simplest way to achieve this.
I added Libray Files. and follow the code :
[PayPal getPayPalInst].feePayer = feePayer;
[PayPal getPayPalInst].shippingEnabled = shippingSwitch.on;
[PayPal getPayPalInst].dynamicAmountUpdateEnabled = dynamicAmountCalculationSwitch.on;
if (isAdvanced) {
[[PayPal getPayPalInst] advancedCheckoutWithPayment:advancedPayment];
} else {
[[PayPal getPayPalInst] checkoutWithPayment:payment];
}
For payment action it will getting erro
Please Help in this issue.
Thanks In Advance.

After importing entire paypal library use this code
#import "PayPal.h"
typedef enum PaymentStatuses {
PAYMENTSTATUS_SUCCESS,
PAYMENTSTATUS_FAILED,
PAYMENTSTATUS_CANCELED,
} PaymentStatus;
#interface Paybypal : UIViewController<PayPalPaymentDelegate>{
#private
CGFloat y;
BOOL resetScrollView;
PaymentStatus status;
}
#property(nonatomic,retain)NSString *details;
#property(nonatomic,retain)NSDecimalNumber *totalvaluemin;
in .m file
#import "Paybypal.h"
#import "PayPalPayment.h"
#import "PayPalAdvancedPayment.h"
#import "PayPalAmounts.h"
#import "PayPalReceiverAmounts.h"
#import "PayPalAddress.h"
#import "PayPalInvoiceItem.h"
#import "SuccessViewController.h"
#define SPACING 3.
#interface Paybypal ()
#end
#implementation Paybypal
#synthesize details,totalvaluemin;
-(void)addLabelWithText:(NSString *)text andButtonWithType:(PayPalButtonType)type withAction:(SEL)action {
UIFont *font = [UIFont boldSystemFontOfSize:14.];
CGSize size = [text sizeWithFont:font];
UIButton *button = [[PayPal getPayPalInst] getPayButtonWithTarget:self andAction:action andButtonType:type];
CGRect frame = button.frame;
frame.origin.x = round((self.view.frame.size.width - button.frame.size.width) / 2.);
frame.origin.y = round(y + size.height);
button.frame = frame;
[self.view addSubview:button];
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(frame.origin.x, y, size.width, size.height)] autorelease];
label.font = font;
label.text = text;
label.backgroundColor = [UIColor clearColor];
[self.view addSubview:label];
y += size.height + frame.size.height + SPACING;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
self.view.autoresizesSubviews = FALSE;
UIColor *color = [UIColor groupTableViewBackgroundColor];
if (CGColorGetPattern(color.CGColor) == NULL) {
color = [UIColor lightGrayColor];
}
self.title = #"";
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Background.JPG"]];
backgroundView.frame = self.view.bounds;
[[self view] addSubview:backgroundView];
status = PAYMENTSTATUS_CANCELED;
y = 2.;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake((self.view.frame.size.width - 125), 222, 75, 25);
[button setTitle:#"" forState:UIControlStateNormal];
[button addTarget:self action:#selector(RetryInitialization) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[self addLabelWithText:#"" andButtonWithType:BUTTON_294x43 withAction:#selector(simplePayment)];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)simplePayment {
[PayPal getPayPalInst].shippingEnabled = TRUE;
[PayPal getPayPalInst].dynamicAmountUpdateEnabled = TRUE;
[PayPal getPayPalInst].feePayer = FEEPAYER_EACHRECEIVER;
PayPalPayment *payment = [[[PayPalPayment alloc] init] autorelease];
payment.recipient = #"receiver email id";
payment.paymentCurrency = #"USD";
payment.description = [NSString stringWithFormat:#"%#",details];
payment.merchantName = #"receiver name";
payment.subTotal = totalvaluemin;
payment.invoiceData = [[[PayPalInvoiceData alloc] init] autorelease];
payment.invoiceData.totalShipping = [NSDecimalNumber decimalNumberWithString:#"0"];
payment.invoiceData.totalTax = [NSDecimalNumber decimalNumberWithString:#"0.00"];
payment.invoiceData.invoiceItems = [NSMutableArray array];
PayPalInvoiceItem *item = [[[PayPalInvoiceItem alloc] init] autorelease];
item.totalPrice = payment.subTotal;
item.name =[NSString stringWithFormat:#"%#",details];
[payment.invoiceData.invoiceItems addObject:item];
[[PayPal getPayPalInst] checkoutWithPayment:payment];
}
#pragma mark -
#pragma mark PayPalPaymentDelegate methods
-(void)RetryInitialization
{
//[PayPal initializeWithAppID:#"APP-80W284485P519543T" forEnvironment:ENV_SANDBOX];
//DEVPACKAGE
//[PayPal initializeWithAppID:#"APPLIVEID" forEnvironment:ENV_LIVE];
// [PayPal initializeWithAppID:#"anything" forEnvironment:ENV_NONE];
}
- (void)paymentSuccessWithKey:(NSString *)payKey andStatus:(PayPalPaymentStatus)paymentStatus {
NSString *severity = [[PayPal getPayPalInst].responseMessage objectForKey:#"severity"];
NSLog(#"severity: %#", severity);
NSString *category = [[PayPal getPayPalInst].responseMessage objectForKey:#"category"];
NSLog(#"category: %#", category);
NSString *errorId = [[PayPal getPayPalInst].responseMessage objectForKey:#"errorId"];
NSLog(#"errorId: %#", errorId);
NSString *message = [[PayPal getPayPalInst].responseMessage objectForKey:#"message"];
NSLog(#"message: %#", message);
status = PAYMENTSTATUS_SUCCESS;
}
- (void)paymentFailedWithCorrelationID:(NSString *)correlationID {
NSString *severity = [[PayPal getPayPalInst].responseMessage objectForKey:#"severity"];
NSLog(#"severity: %#", severity);
NSString *category = [[PayPal getPayPalInst].responseMessage objectForKey:#"category"];
NSLog(#"category: %#", category);
NSString *errorId = [[PayPal getPayPalInst].responseMessage objectForKey:#"errorId"];
NSLog(#"errorId: %#", errorId);
NSString *message = [[PayPal getPayPalInst].responseMessage objectForKey:#"message"];
NSLog(#"message: %#", message);
status = PAYMENTSTATUS_FAILED;
}
- (void)paymentCanceled {
status = PAYMENTSTATUS_CANCELED;
}
- (void)paymentLibraryExit {
UIAlertView *alert = nil;
switch (status) {
case PAYMENTSTATUS_SUCCESS:
[self.navigationController pushViewController:[[[SuccessViewController alloc] init] autorelease] animated:TRUE];
break;
case PAYMENTSTATUS_FAILED:
alert = [[UIAlertView alloc] initWithTitle:#"Order failed"
message:#"Your order failed. Touch \"Pay with PayPal\" to try again."
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
break;
case PAYMENTSTATUS_CANCELED:
alert = [[UIAlertView alloc] initWithTitle:#"Order canceled"
message:#"You canceled your order. Touch \"Pay with PayPal\" to try again."
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
break;
}
[alert show];
[alert release];
}
- (PayPalAmounts *)adjustAmountsForAddress:(PayPalAddress const *)inAddress andCurrency:(NSString const *)inCurrency andAmount:(NSDecimalNumber const *)inAmount
andTax:(NSDecimalNumber const *)inTax andShipping:(NSDecimalNumber const *)inShipping andErrorCode:(PayPalAmountErrorCode *)outErrorCode {
//do any logic here that would adjust the amount based on the shipping address
PayPalAmounts *newAmounts = [[[PayPalAmounts alloc] init] autorelease];
newAmounts.currency = #"SGD";
newAmounts.payment_amount = (NSDecimalNumber *)inAmount;
//change tax based on the address
if ([inAddress.state isEqualToString:#"CA"]) {
newAmounts.tax = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%.2f",[inAmount floatValue] * .1]];
} else {
newAmounts.tax = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%.2f",[inAmount floatValue] * .08]];
}
newAmounts.shipping = (NSDecimalNumber *)inShipping;
//if you need to notify the library of an error condition, do one of the following
//*outErrorCode = AMOUNT_ERROR_SERVER;
//*outErrorCode = AMOUNT_CANCEL_TXN;
//*outErrorCode = AMOUNT_ERROR_OTHER;
return newAmounts;
}
- (NSMutableArray *)adjustAmountsAdvancedForAddress:(PayPalAddress const *)inAddress andCurrency:(NSString const *)inCurrency
andReceiverAmounts:(NSMutableArray *)receiverAmounts andErrorCode:(PayPalAmountErrorCode *)outErrorCode {
NSMutableArray *returnArray = [NSMutableArray arrayWithCapacity:[receiverAmounts count]];
for (PayPalReceiverAmounts *amounts in receiverAmounts) {
//leave the shipping the same, change the tax based on the state
if ([inAddress.state isEqualToString:#"CA"]) {
amounts.amounts.tax = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%.2f",[amounts.amounts.payment_amount floatValue] * .1]];
} else {
amounts.amounts.tax = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%.2f",[amounts.amounts.payment_amount floatValue] * .08]];
}
[returnArray addObject:amounts];
}
//if you need to notify the library of an error condition, do one of the following
//*outErrorCode = AMOUNT_ERROR_SERVER;
//*outErrorCode = AMOUNT_CANCEL_TXN;
//*outErrorCode = AMOUNT_ERROR_OTHER;
return returnArray;
}
#pragma mark -
#pragma mark UITextFieldDelegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return TRUE;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
resetScrollView = FALSE;
return TRUE;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
resetScrollView = TRUE;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.3];
[UIView setAnimationBeginsFromCurrentState:TRUE];
self.view.frame = CGRectMake(0., -216., self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
if (resetScrollView) {
resetScrollView = FALSE;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:.3];
[UIView setAnimationBeginsFromCurrentState:TRUE];
self.view.frame = CGRectMake(0., 0., self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];
}
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return TRUE;
}
#end

Related

Identifying an UIImageView without tag

I have some generic generated ImageViews in a scrollView each of these images have 2 gestureRecognizer for single/double tapping on the ImageView. Now my problem is how to identify whether the ImageView was tapped for first or second time. In some scenarios it's easy to use the tag of an ImageView, but I have two different gestureRecognizer on each ImageView and every gestureRecognizer uses a different identification method based on the tag number, to identify the image.
Here I generate the ImageViews dynamically:
-(void) initLevels{
_level = [Level alloc];
_unit = [Unit alloc];
self->_units = [[NSMutableArray alloc] init];
_keys = [[NSMutableArray alloc] init]
;
int x = 0;
int y = 0;
int i = 0;
for (NSObject *object in self->_levels) {
if ([object isKindOfClass:_level.class] && i != 0) {
x = x + MARGIN_RIGHT + OBJECT_WIDTH;
y = 0;
}
else if ([object isKindOfClass:_unit.class]){
_unit = (Unit *) object;
[self->_units addObject:_unit.description];
UIImageView *imageView = [[UIImageView alloc] initWithImage:self.box];
[imageView setFrame:CGRectMake(x, y, OBJECT_WIDTH, BOX_HEIGHT)];
imageView.highlighted = TRUE;
imageView.tag = i; //when this is not outlined the gestureRecognizer for singleTapping works but on the other hand the double tap gestureRecognizer just works for the first object, because its' tag is set on 0.
UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(unitDoubleTapped:)];
doubleTapGesture.numberOfTapsRequired = 2;
imageView.userInteractionEnabled = YES;
[imageView addGestureRecognizer:doubleTapGesture];
UITapGestureRecognizer *singleTapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(unitSingleTapped:)];
singleTapGesture.numberOfTapsRequired = 1;
//telling the singleTapGesture to fail the doubleTapGesture, so both doesn't fire at the same time
[singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
[imageView addGestureRecognizer:singleTapGesture];
UILabel *labelHeadline = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 220, 20)];
[labelHeadline setFont:[UIFont boldSystemFontOfSize:12]];
labelHeadline.textAlignment = NSTextAlignmentCenter;
[labelHeadline setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
labelHeadline.text = _unit.headline;
labelHeadline.numberOfLines = 0;
[labelHeadline sizeToFit];
UILabel *labelPrice = [LabelUtils deepLabelCopy:labelHeadline withText:[NSString stringWithFormat:#"Price: %#",_unit.price] withFrame:NO];
[labelPrice setTextAlignment:NSTextAlignmentLeft];
[labelPrice setFrame:CGRectMake(labelHeadline.frame.origin.x, labelHeadline.frame.origin.y + labelHeadline.frame.size.height + 2, 220, 20)];
UILabel *labelCRM = [LabelUtils deepLabelCopy:labelHeadline withText:[NSString stringWithFormat:#"CRM: %#", _unit.crm] withFrame:NO];
[labelCRM setTextAlignment:NSTextAlignmentLeft];
[labelCRM setFrame:CGRectMake(labelPrice.frame.origin.x, labelPrice.frame.origin.y + labelPrice.frame.size.height + 2, 220, 20)];
UITextView *textView= [[UITextView alloc] initWithFrame:CGRectMake(0,0, OBJECT_WIDTH, OBJECT_HEIGHT)];
[textView addSubview:labelHeadline];
[textView addSubview:labelPrice];
[textView addSubview:labelCRM];
[textView setUserInteractionEnabled:NO];
[textView setEditable:NO];
textView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0];
textView.textAlignment = NSTextAlignmentLeft;
[imageView addSubview:textView];
[_scrollView addSubview:imageView];
y = y + MARGIN_BOTTOM + BOX_HEIGHT;
}
[self->_keys addObject:[NSNumber numberWithInt:i]];
i++;
}//remove the last keys which are to much in the _keys array
while ([self->_keys count] > ([self->_units count])) {
[_keys removeLastObject];
i--;
}
self.contents = [NSDictionary dictionaryWithObjects:self->_units forKeys:_keys];
}
Here is the code for the two gesture Recognizer
-(void)unitDoubleTapped:(UIGestureRecognizer *)gestureRecognizer{
self->_unitViewForDoubleTapIdentification = (UIImageView *)gestureRecognizer.view;
switch (self->_unitViewForDoubleTapIdentification.tag) {
case 0:
[_unitViewForDoubleTapIdentification setHighlightedImage:self.transparentBox];
self->_unitViewForDoubleTapIdentification.tag = 1;
break;
case 1:
[_unitViewForDoubleTapIdentification setHighlightedImage:self.box];
self->_unitViewForDoubleTapIdentification.tag = 0;
break;
default:
break;
}
}
and Here the singleTap
- (IBAction)unitSingleTapped:(id)sender {
[self dismissAllPopTipViews];
UIGestureRecognizer *gestureRecognizer = [UIGestureRecognizer alloc];
gestureRecognizer = (UIGestureRecognizer *)sender;
UIImageView *imageView = [[UIImageView alloc] init];
imageView = (UIImageView *)gestureRecognizer.view;
if (sender == _currentPopTipViewTarget) {
// Dismiss the popTipView and that is all
self.currentPopTipViewTarget = nil;
}
NSString *contentMessage = nil;
UIImageView *contentView = nil;
NSNumber *key = [NSNumber numberWithInt:imageView.tag];
id content = [self.contents objectForKey:key];
if ([content isKindOfClass:[NSString class]]) {
contentMessage = content;
}
else {
contentMessage = #"A large amount ot text in this bubble\najshdjashdkgsadfhadshgfhadsgfkasgfdasfdhasdkfgaodslfgkashjdfg\nsjfkasdfgkahdjsfghajdsfgjakdsfgjjakdsfjgjhaskdfjadsfgjdsfahsdafhjajdskfhadshfadsjfhadsjlfkaldsfhfldsa\ndsfgahdsfgajskdfgkafd";
}
NSArray *colorScheme = [_colorSchemes objectAtIndex:foo4random()*[_colorSchemes count]];
UIColor *backgroundColor = [colorScheme objectAtIndex:0];
UIColor *textColor = [colorScheme objectAtIndex:1];
CMPopTipView *popTipView;
if (contentView) {
popTipView = [[CMPopTipView alloc] initWithCustomView:contentView];
}
else {
popTipView = [[CMPopTipView alloc] initWithMessage:contentMessage];
}
[popTipView presentPointingAtView:imageView inView:self.view animated:YES];
popTipView.delegate = self;
popTipView.disableTapToDismiss = YES;
popTipView.preferredPointDirection = PointDirectionUp;
if (backgroundColor && ![backgroundColor isEqual:[NSNull null]]) {
popTipView.backgroundColor = backgroundColor;
}
if (textColor && ![textColor isEqual:[NSNull null]]) {
popTipView.textColor = textColor;
}
popTipView.animation = arc4random() % 2;
popTipView.has3DStyle = (BOOL)(arc4random() % 2);
popTipView.dismissTapAnywhere = YES;
[popTipView autoDismissAnimated:YES atTimeInterval:3.0];
[_visiblePopTipViews addObject:popTipView];
self.currentPopTipViewTarget = sender;
}
Hope you can help me, thanks in advance.
that's a lot of code to go through.. but I add more identifiers to UIViews (ie other than the tag identifier) by using obj-c runtime associative references..
So this is a category I attach to my UIView:
#import "UIView+Addons.h"
#import <objc/runtime.h>
#define kAnimationDuration 0.25f
#implementation UIView (Addons)
static char infoKey;
static char secondaryInfoKey;
-(id)info {
return objc_getAssociatedObject(self, &infoKey);
}
-(void)setInfo:(id)info {
objc_setAssociatedObject(self, &infoKey, info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(id)secondaryInfo {
return objc_getAssociatedObject(self, &secondaryInfoKey);
}
-(void)setSecondaryInfo:(id)info {
objc_setAssociatedObject(self, &secondaryInfoKey, info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#end
here is an example of my own code where I use the above to address a problem similar to the one you're facing:
if (![[view info] boolValue]) { // not selected?
self.moveToFolderNumber = [view secondaryInfo];
[view setInfo:#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];

Multiple rating bars with DYRateView

I have a view with 3 ratings bars on it.
How do I tell them apart in the code? Right now if I change the top one it sees it fine but if I then change either or the other two it cannot separate them from one another.
The code is from git https://github.com/dyang/DYRateView
- (void)changedToNewRate:(NSNumber *)rate {
NSString *rating = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"rating: %#",rating);
}
This is where is sees the changing.
And this is the .m file
#import "Survey.h"
#implementation Survey
#synthesize btnSubmit;
- (void)setUpEditableRateView {
DYRateView *rateService = [[DYRateView alloc] initWithFrame:CGRectMake(0, 55, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateService.padding = 20;
rateService.alignment = RateViewAlignmentCenter;
rateService.editable = YES;
rateService.delegate =self;
[scroller addSubview:rateService];
[rateService release];
DYRateView *rateFood = [[DYRateView alloc] initWithFrame:CGRectMake(0, 130, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateFood.padding = 20;
rateFood.alignment = RateViewAlignmentCenter;
rateFood.editable = YES;
rateFood.delegate = self;
[scroller addSubview:rateFood];
[rateFood release];
DYRateView *rateCleanliness = [[DYRateView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateCleanliness.padding = 20;
rateCleanliness.alignment = RateViewAlignmentCenter;
rateCleanliness.editable = YES;
rateCleanliness.delegate = self;
[scroller addSubview:rateCleanliness];
[rateCleanliness release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)changedToNewRate:(NSNumber *)rate {
NSString *rating = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"rating: %#",rating);
}
- (IBAction)btnSubmit:(id)sender{
}
-(IBAction)mainMenu{
[self dismissModalViewControllerAnimated:YES];
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320, 600)];
scroller.BackgroundColor = [UIColor clearColor];
[self setUpEditableRateView];
[btnSubmit useGreenConfirmStyle];
}
- (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
UPDATE
ok with the new code I added an if statement
- (void)rateView:(DYRateView *)rateView changedToNewRate:(NSNumber *)rate {
NSString *barName = [NSString stringWithFormat:#"%#", rateView];
if (barName == #"rateView1") {
NSString *bar1 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 1: %#",bar1);
}else if(barName == #"rateView2"){
NSString *bar2 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 2: %#",bar2);
}else{
NSLog(#"NO BAR: %#",barName);
}
self.rateLabel.text = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
}
It works however Instead of getting back "rateView1" or 2 or 3. I get back
NO BAR: <DYRateView: 0x78229b0; frame = (0 40; 320 20); opaque = NO; layer =
<CALayer:0x7824900>>
Which is correct in nature but I was hoping for the name of the rateView such as "rateView1"
SOLUTION:
in .h file #property your 2 or 3 bars
#property(nonatomic, retain) DYRateView *rateView1,*rateView2;
in .m #synthesize them
#synthesize rateView1;
#synthesize rateView2;
then
(void)setUpEditableRateView {
rateView1 = [[DYRateView alloc] initWithFrame:CGRectMake(0, 40, self.view.bounds.size.width, 20) fullStar:[UIImage imageNamed:#"StarFullLarge.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge.png"]];
rateView1.padding = 20;
rateView1.alignment = RateViewAlignmentCenter;
rateView1.editable = YES;
rateView1.delegate = self;
[self.view addSubview:rateView1];
[rateView1 release];
rateView2 = [[DYRateView alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 20) fullStar:[UIImage imageNamed:#"StarFullLarge.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge.png"]];
rateView2.padding = 20;
rateView2.alignment = RateViewAlignmentCenter;
rateView2.editable = YES;
rateView2.delegate = self;
[self.view addSubview:rateView2];
[rateView2 release];
// Set up a label view to display rate
self.rateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 80, self.view.bounds.size.width, 20)] autorelease];
self.rateLabel.textAlignment = UITextAlignmentCenter;
self.rateLabel.text = #"Tap above to rate";
[self.view addSubview:self.rateLabel];
}
Then Finally
- (void)rateView:(DYRateView *)rateView changedToNewRate:(NSNumber *)rate {
if (rateView == rateView1) {
NSString *bar1 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 1: %#",bar1);
}else if(rateView == rateView2){
NSString *bar2 = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
NSLog(#"bar 2: %#",bar2);
}else{
NSLog(#"NO BAR: %#",rateView);
}
self.rateLabel.text = [NSString stringWithFormat:#"Rate: %d", rate.intValue];
}
Thanks for using DYRateView!
The current version of DYRateView doesn't support listening to multiple instances all at the same time, but that doesn't mean that we can't do that. :)
If you don't mind updating the source code, you can find a method named notifyDelegate in DYRateView.m, and change [self.delegate performSelector:#selector(changedToNewRate:) withObject:[NSNumber numberWithFloat:self.rate]] to something like [self.delegate performSelector:#selector(rateView:changedToNewRate:) withObject:self withObject:[NSNumber numberWithFloat:self.rate]]. In this way you are able to pass the rateView itself as a parameter to its listener.
I haven't tried the above code yet as I don't have access to my Mac at this point, but I think this should give you an idea regarding how to achieve your goal.
I just set the tag for each of my rateviews to tell them apart, so in your example, I add a tag to each one:
#define serviceTag 1
#define foodTag 2
#define cleanlinessTag 3
- (void)setUpEditableRateView {
DYRateView *rateService = [[DYRateView alloc] initWithFrame:CGRectMake(0, 55, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateService.padding = 20;
rateService.alignment = RateViewAlignmentCenter;
rateService.editable = YES;
rateService.tag = serviceTag;
rateService.delegate =self;
[scroller addSubview:rateService];
[rateService release];
DYRateView *rateFood = [[DYRateView alloc] initWithFrame:CGRectMake(0, 130, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateFood.padding = 20;
rateFood.alignment = RateViewAlignmentCenter;
rateFood.editable = YES;
rateFood.tag = foodTag;
rateFood.delegate = self;
[scroller addSubview:rateFood];
[rateFood release];
DYRateView *rateCleanliness = [[DYRateView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 40) fullStar:[UIImage imageNamed:#"StarFullLarge#2x.png"] emptyStar:[UIImage imageNamed:#"StarEmptyLarge#2x.png"]];
rateCleanliness.padding = 20;
rateCleanliness.alignment = RateViewAlignmentCenter;
rateCleanliness.editable = YES;
rateCleanliness.delegate = self;
rateCleanliness.tag = cleanlinessTag;
[scroller addSubview:rateCleanliness];
[rateCleanliness release];
}
Then, in the delegate method, you can just check the tag:
- (void)rateView:(DYRateView *)rateView changedToNewRate:(NSNumber *)rate {
switch (rateView.tag) {
case foodTag:
// Do something for food
break;
case serviceTag:
// Do something for service
break;
case cleanlinessTag:
// Do something for cleanliness
break;
default:
break;
}
}

tableView:didSelectRowAtIndexPath not firing after swipe gesture is called

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.