Tuesday, 30 December 2014

Getting row of UITableView cell on button press


CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];


NSLog(@"index: %ld",(long)indexPath.section);

NSLog(@"index: %ld",(long)indexPath.row);

Add a multiple buttons to a view programatically

for( int i = 0; i < 5; i++ ) {
  UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [aButton setTag:i];
  [aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
  [aView addSubview:aButton];
}

// then ...

- (void)buttonClicked:(UIButton*)button
{
  NSLog(@"Button %ld clicked.", (long int)[button tag]);
}

Friday, 19 December 2014

Insert new cells in a UITableView (OR) Middle of the UITableView



[self.dataSourceArray insertObject:object atIndex:indexPath.row];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];


(OR)


    NSInteger row = 1;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];

    [self.dataSourceArray insertObject:object atIndex:indexPath.row];
    [self.ItineraryTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

    

Monday, 20 October 2014

How to add a button to specific row in tableview

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];

    UIButton *button = nil;
    
   // cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    if (cell == nil)
    {
       //  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        
        button = [[UIButton alloc] initWithFrame:CGRectZero];
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.tag = 579;
       [button setTitle:@"Show View" forState:UIControlStateNormal];
       [cell.contentView addSubview:button];
    }
    
    if (displayObject11.count != 0) {            
        
            if (indexPath.row == 2) {
                button = (UIButton*)[cell viewWithTag:579];
                button.frame = CGRectMake(180.0, 10, 160.0, 40.0);
              }              
    }    
    return cell;

}

Tuesday, 23 September 2014

String file read/write in plist

First you create one plist file. Here lock is a plist file, unlocked is a string name. ulocked string create inside plist file.

Write:

    NSString *locat = [[NSBundle mainBundle]pathForResource:@"Plist_filename" ofType:@"plist"];
    NSMutableDictionary *un_lock = [[NSMutableDictionary alloc]initWithContentsOfFile:locat];
    [un_lock setObject:value forKey:@"plist_keyname"];

    [un_lock writeToFile:locat atomically:YES];

(OR)

          NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
              NSString *documentsDirectory = [sysPaths objectAtIndex:0];
              NSString *filePath =  [documentsDirectory stringByAppendingPathComponent:@"lock.plist"];
              NSMutableDictionary *plistDict; // needs to be mutable
              if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                  plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
              } else {
                  // Doesn't exist, start with an empty dictionary
                  plistDict = [[NSMutableDictionary alloc] init];
              }
    
              [plistDict setObject:@"1"forKey:@"unlocked"];

              [plistDict writeToFile:filePath atomically:YES];


Read: 

   NSString *locat = [[NSBundle mainBundle]pathForResource:@"plist_filename" ofType:@"plist"];
    NSDictionary *un_lock = [[NSDictionary alloc]initWithContentsOfFile:locat];
    NSString *str = [un_lock objectForKey:@"plist_keyname"];

(OR)


   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path =[[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"lock.plist"]];
    NSDictionary *savedStock = [[NSDictionary alloc] initWithContentsOfFile: path];

    NSString *str = [savedStock objectForKey:@"unlocked"];

Monday, 1 September 2014

UITextField how to disable the paste?

iOS 7:


- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
    }];
    return [super canPerformAction:action withSender:sender];

}

Tuesday, 1 July 2014

Remove first and last character from NSString

Remove First character from NSString:

NSString *string = @"This is sample string";
NSString *newString = [str substringFromIndex:1];
NSLog(@"New string: %@", newString);

Remove Last character from NSString:

NSString *string = @"This is sample string";
NSString *Newstring = [string substringToIndex:[string length]-1];


Thursday, 19 June 2014

Dismiss keyboard when touching outside of textfield

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      [self.view endEditing:YES];
}


(OR)


- (IBAction)btnShowPickerClickRateType:(id)sender {
[self.view endEditing:YES];
}

UITableviewcell while clicking the textfield move up the tableview

CGFloat animatedDistance;

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;

 - (void)textFieldDidBeginEditing:(UITextField *)textField
{
 CGRect textFieldRect =
        [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect =
        [self.view.window convertRect:self.view.bounds fromView:self.view];
        CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
CGFloat numerator =
    midline - viewRect.origin.y
        - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
CGFloat denominator =
    (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
        * viewRect.size.height;
CGFloat heightFraction = numerator / denominator;
if (heightFraction < 0.0)
{
    heightFraction = 0.0;
}
else if (heightFraction > 1.0)
{
    heightFraction = 1.0;
}
UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait ||
    orientation == UIInterfaceOrientationPortraitUpsideDown)
{
    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
}
else
{
    animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
}
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
   
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
   
    [self.view setFrame:viewFrame];
   
    [UIView commitAnimations];
    }
 
    - (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
   
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
   
    [self.view setFrame:viewFrame];
   
    [UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

Hide keyboard when UITextField is inside a TableView Cell

@interface ViewController () {
   UITextField *_textFieldBeingEdited;
}
@end

- (void)textFieldDidBeginEditing:(UITextField *)textField {
   _textFieldBeingEdited = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
   // no need to resignFirstResponder here.
   _textFieldBeingEdited = nil;
}

- (void)tableView:(UITableView *)tableView
          didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   if (_textFieldBeingEdited) {
     [_textFieldBeingEdited resignFirstResponder];
   }
   ...
}

Monday, 9 June 2014

How to check jsonobjects Nsdictonary or Nsarray

  id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
                

  if([jsonObject isKindOfClass:[NSDictionary class]]) {
                    NSLog(@"Dictionary");
                }
                else if([jsonObjects isKindOfClass:[NSArray class]]) {
                    NSLog(@"Array");

                }

Wednesday, 28 May 2014

Convert date in MM/dd/yyyy format

NSString *str = @"2012-10-30"; /// here this is your date with format yyyy-MM-dd

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; //// here set format of date which is in your output date (means above str with format)

NSDate *date = [dateFormatter dateFromString: str]; // here you can fetch date from string with define format

dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];// here set format which you want...

NSString *convertedString = [dateFormatter stringFromDate:date]; here convert date in NSString
NSLog(@"Converted String : %@",convertedString);

Wednesday, 21 May 2014

Sorting an NSArray in ascending order

 NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            if ([obj1 intValue] < [obj2 intValue]) return NSOrderedAscending;
            else return NSOrderedDescending;
        }];
NSLog(@"sorted ~~~~~~~ %@",sorted);

(OR)

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [array_value_name sortedArrayUsingDescriptors:sortDescriptors];

Tuesday, 6 May 2014

Uitableviewcell disable the uibutton for editing time

      for (int row = 0, rowCount = [myTable numberOfRowsInSection:0]; row < rowCount; ++row) {
            
            UITableViewCell *cell = [myTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
            UIButton *forwordbtn1 = (UIButton *)[cell viewWithTag:410];
            forwordbtn1.enabled = NO;
        }


Here 410 is uitableviewcell button tag value.

resize UISwitch button

mySwitch.transform = CGAffineTransformMakeScale(0.75, 0.75);

Friday, 17 January 2014

TextField validation

-(BOOL)validateFname:(NSString*)name {    
    if ([name length ]== 0)  {
        return NO;
    }    
    return YES;

}

- (IBAction)btnSave_Clicked:(id)sender
{
    if(![self validateFname:nametxt.text]) {
        connectFailMessage = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Food items can not be empty!"  delegate: self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        connectFailMessage.tag = 1002;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(95,15,22, 22)]; 
        NSString *imgPath = [[NSString alloc] initWithString:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"button_cancel.png"]];
        UIImage *yourImage = [[UIImage alloc] initWithContentsOfFile:imgPath];
        [imageView setImage:yourImage];
        [yourImage release];
        [imgPath release];
        [connectFailMessage addSubview:imageView];
        [connectFailMessage show];
        UILabel *theTitle1 = [connectFailMessage valueForKey:@"_titleLabel"];
        [theTitle1 setFont:[UIFont fontWithName:@"Avenir bold" size:16]];
        [theTitle1 setTextColor:[UIColor redColor]];
        UILabel *theBody1 = [connectFailMessage valueForKey:@"_bodyTextLabel"];
        [theBody1 setFont:[UIFont fontWithName:@"Avenir" size:15]];
        [theBody1 setTextColor:[UIColor whiteColor]];
        
        return;
    }
}

Monday, 13 January 2014

Create Customize ActivityIndicatorView

   .h file

@interface RootViewController : UIViewController {
UIActivityIndicatorView *activityView;
UIView *loadingView;
UILabel *loadingLabel;
}
@property (nonatomic, retain) UIActivityIndicatorView * activityView;

@property (nonatomic, retain) UIView *loadingView;
@property (nonatomic, retain) UILabel *loadingLabel;

.m file

#import <QuartzCore/QuartzCore.h>

@synthesize activityView;
@synthesize loadingView;
@synthesize loadingLabel;

  loadingView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
     loadingView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
     loadingView.clipsToBounds = YES;
     loadingView.layer.cornerRadius = 10.0;
     activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
     activityView.frame = CGRectMake(65, 40, activityView.bounds.size.width, activityView.bounds.size.height);
    [loadingView addSubview:activityView];
    loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    loadingLabel.backgroundColor = [UIColor clearColor];
    loadingLabel.textColor = [UIColor whiteColor];
    loadingLabel.adjustsFontSizeToFitWidth = YES;
    loadingLabel.textAlignment = UITextAlignmentCenter;
    loadingLabel.text = @"Loading...";
    [loadingView addSubview:loadingLabel]; 
    [self.view addSubview:loadingView];

[activityView startAnimating];

[activityView stopAnimating];

[loadingView removeFromSuperview];