Friday, 20 December 2013

Removing extra separator lines for empty rows in UITableView

- (void) viewDidLoad
{
  [super viewDidLoad];

  self.tableView.tableFooterView = [[[UIView alloc] init] autorelease];
}

Tuesday, 17 December 2013

iPhone - Create custom UITableViewCell top and bottom borders

tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

// Draw top border only on first cell
if (indexPath.row == 0) {
    UIView *topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 1)];
    topLineView.backgroundColor = [UIColor grayColor];
    [cell.contentView addSubview:topLineView];
}

UIView *bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.bounds.size.height, self.view.bounds.size.width, 1)];
bottomLineView.backgroundColor = [UIColor grayColor];

[cell.contentView addSubview:bottomLineView];

Tuesday, 10 December 2013

How to check document directory file your image is there or not

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"/progress/before.png"];

  if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath])
    {
       //file not exits in Document Directories
        imageviewname.image = [UIImage imageNamed:@"add_photo_block_hires.png"];
    }
    else
    {
        //file exist in Document Directories
         imageviewname.image =[UIImage imageWithContentsOfFile:imagePath1];

    }

Monday, 9 December 2013

How to remove uiview from uiscrollview in iphone

      if([viewname superview]!=nil)
        {
            for(UIView *subview in [scrollviewname subviews]) {
                if([subview isKindOfClass:[viewname class]]) {
                    [subview removeFromSuperview];
                }
            }

        }

Friday, 6 December 2013

Pop back to a specific viewcontroller in the navigationController

[self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:2] animated:YES];

Wednesday, 27 November 2013

How to disable the scrollbar in scrollview

[scrollview setShowsHorizontalScrollIndicator:NO];
[scrollview setShowsVerticalScrollIndicator:NO];

Tuesday, 26 November 2013

Wednesday, 20 November 2013

How to create folder and save multiple image for document directory in ios

.h file

@interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    UIImagePickerController *picker;
    UIImage *image;
}
-(IBAction)ChooseExisting;

.m file

-(IBAction)ChooseExisting{
    picker = [[UIImagePickerController alloc]init];
    picker.delegate=self;
    [picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [self presentViewController:picker animated:YES completion:NULL];
    
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:NULL];    
    if (image != nil)
    {      
        NSError *error;
        NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *dataPath = [aDocumentsDirectory stringByAppendingPathComponent:@"Image"];
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];       
      
        NSDateFormatter *format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyyMMddHHmmss"];
        NSDate *now = [NSDate date];
        NSString *retStr = [format stringFromDate:now];        
                
            NSString *anImageName = [NSString stringWithFormat:@"%@.png", retStr];
             NSString *anImagePath = [NSString stringWithFormat:@"%@/%@", dataPath, anImageName];
            NSLog(@"the path is=%@",anImagePath);
            
            NSData *anImageData = UIImagePNGRepresentation(image);
            [anImageData writeToFile:anImagePath atomically:YES];      
       
    }
    
}

How to save image document directory in ios

.h file

@interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
 {
    UIImagePickerController *picker;
    UIImage *image;
}
-(IBAction)ChooseExisting;

- (IBAction)btnSave:(id)sender;


.m file

-(IBAction)ChooseExisting{
    picker = [[UIImagePickerController alloc]init];
    picker.delegate=self;
    [picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [self presentViewController:picker animated:YES completion:NULL];
    
}
- (IBAction)btnSave:(id)sender {    
    if (image != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:
                          [NSString stringWithFormat: @"imagename.png"]];
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];     
    }
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

Friday, 8 November 2013

Validate length and restrict textfield to Numeric, alphanumeric, and alpha characters only

#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC @"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
#define MAX_LENGTH 25


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if(textField== textfieldname)
    {           
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        
        NSCharacterSet *unacceptedInput =
        [[NSCharacterSet characterSetWithCharactersInString:ALPHA_NUMERIC] invertedSet];

        if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
            return NO;
        else
            return YES&&(newLength < MAX_LENGTH);
        return YES;
    }else{
        return NO;
    }
}

allow only alphanumeric characters for a UITextField

#define ALPHA                   @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC                 @"1234567890"
#define ALPHA_NUMERIC           ALPHA NUMERIC

// Make sure you are the text fields 'delegate', then this will get called before text gets changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // This will be the character set of characters I do not want in my text field.  Then if the replacement string contains any of the characters, return NO so that the text does not change.
    NSCharacterSet *unacceptedInput = nil;

    // I have 4 types of textFields in my view, each one needs to deny a specific set of characters:
    if (textField == emailField) {
        //  Validating an email address doesnt work 100% yet, but I am working on it....  The rest work great!
        if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
        } else {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
        }
    } else if (textField == phoneField) {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMERIC] invertedSet];
    } else if (textField == fNameField || textField == lNameField) {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
    } else {
        unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
    }

    // If there are any characters that I do not want in the text field, return NO.
    return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}

Tuesday, 29 October 2013

Action on UILabel in iphone

[titleLbl setUserInteractionEnabled:YES];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelButton:)];
[tapGestureRecognizer setNumberOfTapsRequired:1];
[titleLbl addGestureRecognizer:tapGestureRecognizer];

[tapGestureRecognizer release];

Friday, 4 October 2013

UIScrollview Autolayout Issue

.h file

@property (assign,nonatomic) CGPoint scrollviewContentOffsetChange;

.m file

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.scrollView.contentOffset = CGPointZero;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.scrollviewContentOffsetChange = self.scrollView.contentOffset;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
     self.scrollView.contentOffset = self.scrollviewContentOffsetChange;
}

Wednesday, 18 September 2013

clear uitextfield

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([textField.text isEqualToString:@""] || [[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
    {
        [textField setText:@""];
        
    }    

}

Detect backspace in UITextField

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.length > 0 && [text isEqualToString:@""]) {
        NSLog(@"press Backspace.");
    }
    return YES;
}
(OR)
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([string isEqualToString:@""]) {
        return YES;
    }
}

Wednesday, 11 September 2013

UIDatePicker

.h file

@interface ViewController : UIViewController
{
    IBOutlet UIDatePicker *datePicker;
    IBOutlet UILabel *lblResult;

}

.m file

- (void)viewDidLoad
{
    [super viewDidLoad];
      datePicker.date = [NSDate date];    
    [datePicker addTarget:self
              action:@selector(datechange:)
    forControlEvents:UIControlEventValueChanged];
}

- (void)datechange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];

//[df setDateFormat:@"yyyy-MM-dd"];
   df.dateStyle = NSDateFormatterMediumStyle;
lblResult.text = [NSString stringWithFormat:@"%@",
                      [df stringFromDate:datePicker.date]];
}

Monday, 2 September 2013

Removing the image on the left of an UISearchbar

.h file
@interface Search : UIViewController<UISearchBarDelegate>
{
IBOutlet UISearchBar *searchBar;
}
.m file
@interface Search (Private)
- (void)setSearchIconToFavicon;
@end
@implementation Search
- (void)viewDidLoad {
[self setSearchIconToFavicon];
[super viewDidLoad];
}
#pragma mark Private
- (void)setSearchIconToFavicon {
// Really a UISearchBarTextField, but the header is private.
UITextField *searchField = nil;
for (UIView *subview in searchBar.subviews) {
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
break;
}
}
if (searchField) {
UIImage *image = [UIImage imageNamed: @"favicon.png"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
searchField.leftView = iView;
[iView release];
}
} 
@end

change UISearchBar from round to rectangle

  for (UIView *searchBarSubview in [MySearchbarName subviews]) {
        if ([searchBarSubview conformsToProtocol:@protocol(UITextInputTraits)]) {
            @try {
                
                [(UITextField *)searchBarSubview setBorderStyle:UITextBorderStyleRoundedRect];
                [(UITextField *)searchBarSubview setBackgroundColor:[UIColor blackColor]];

                [(UITextField *)searchBarSubview setTextColor:[UIColor whiteColor]];
            }
            @catch (NSException * e) {
                // ignore exception
            }
        }
    }

Saturday, 31 August 2013

Removing the Keyboard when done.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [nameoftextfield resignFirstResponder];

}

Saturday, 24 August 2013

Day Calendar

.h file

@interface ViewController : UIViewController {    
UIImageView *_topBackground;
UIButton *_leftArrow, *_rightArrow;
UILabel *_dateLabel;
IBOutlet UILabel *result;
NSDate *day1;
}

.m file

#import <QuartzCore/QuartzCore.h> 

static NSString *TOP_BACKGROUND_IMAGE                    = @"ma_topBackground.png";
static NSString *LEFT_ARROW_IMAGE                        = @"ma_leftArrow.png";
static NSString *RIGHT_ARROW_IMAGE                       = @"ma_rightArrow.png";
static const unsigned int ARROW_LEFT                     = 100;
static const unsigned int ARROW_RIGHT                    = 101;
static const unsigned int ARROW_WIDTH                    = 48;
static const unsigned int ARROW_HEIGHT                   = 38;
static const unsigned int TOP_BACKGROUND_HEIGHT          = 95

#define CURRENT_CALENDAR [NSCalendar currentCalendar]
#define DATE_COMPONENTS (NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit)

@interface ViewController()

- (void)changeDay:(UIButton *)sender;
- (NSDate *)nextDayFromDate:(NSDate *)date;
- (NSDate *)previousDayFromDate:(NSDate *)date;

@property (readonly) UIImageView *topBackground;
@property (readonly) UIButton *leftArrow;
@property (readonly) UIButton *rightArrow;
@property (readonly) UILabel *dateLabel; 

@property (readonly) UIFont *regularFont;
@property (readonly) UIFont *boldFont;
@property (readonly) NSString *titleText;

@end

@implementation ViewController

- (UIImageView *)topBackground {
if (!_topBackground) {
_topBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:TOP_BACKGROUND_IMAGE]];
}
return _topBackground;
}

- (UIButton *)leftArrow {
if (!_leftArrow) {
_leftArrow = [UIButton buttonWithType:UIButtonTypeCustom];
_leftArrow.tag = ARROW_LEFT;
[_leftArrow setImage:[UIImage imageNamed:LEFT_ARROW_IMAGE] forState:0];
[_leftArrow addTarget:self action:@selector(changeDay:) forControlEvents:UIControlEventTouchUpInside];
}
return _leftArrow;
}

- (UIButton *)rightArrow {
if (!_rightArrow) {
_rightArrow = [UIButton buttonWithType:UIButtonTypeCustom];
_rightArrow.tag = ARROW_RIGHT;
[_rightArrow setImage:[UIImage imageNamed:RIGHT_ARROW_IMAGE] forState:0];
[_rightArrow addTarget:self action:@selector(changeDay:) forControlEvents:UIControlEventTouchUpInside];
}
return _rightArrow;
}

- (UILabel *)dateLabel {
if (!_dateLabel) {
_dateLabel = [[UILabel alloc] init];
_dateLabel.textAlignment = NSTextAlignmentCenter;
_dateLabel.backgroundColor = [UIColor clearColor];
_dateLabel.font = [UIFont boldSystemFontOfSize:18];
_dateLabel.textColor = [UIColor colorWithRed:59/255. green:73/255. blue:88/255. alpha:1];
}
return _dateLabel;
}

- (void)setDay:(NSDate *)date {     
NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
day1 = [CURRENT_CALENDAR dateFromComponents:components];
    [day1 copy];
  self.dateLabel.text = [self titleText];
    
    NSString *str = self.dateLabel.text;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSDate *date1 = [dateFormatter dateFromString: str];
    dateFormatter = [[NSDateFormatter alloc] init] ;
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *convertedString = [dateFormatter stringFromDate:date1];
    result.text = convertedString;
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    NSString *dateString = [dateFormat stringFromDate:today];
    NSLog(@"datestring %@",dateString);
    NSLog(@"cur1: %@",self.dateLabel.text);
       
}

- (void)changeDay:(UIButton *)sender {
   
if (ARROW_LEFT == sender.tag) {
self.day = [self previousDayFromDate:day1];
} else if (ARROW_RIGHT == sender.tag) {
      self.day = [self nextDayFromDate:day1];
}   
}

- (NSDate *)nextDayFromDate:(NSDate *)date {
NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
[components setDay:[components day] + 1];
return [CURRENT_CALENDAR dateFromComponents:components];
}

- (NSDate *)previousDayFromDate:(NSDate *)date {
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    NSString *dateString = [dateFormat stringFromDate:today];
    NSLog(@"datestring %@",dateString);
    NSLog(@"cur1: %@",self.dateLabel.text);
     
    if (dateString == self.dateLabel.text) {    
        NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
        [components setDay:[components day]];
        return [CURRENT_CALENDAR dateFromComponents:components];       
    }else{
         NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
        [components setDay:[components day] - 1];
        return [CURRENT_CALENDAR dateFromComponents:components];
       
    }
}

- (NSString *)titleText {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"]; 
return [NSString stringWithFormat:@"%@",
[formatter stringFromDate:day1]];

- (void)viewDidLoad
{
     self.rightArrow.frame = CGRectMake(280, 60, 20, 20);
    [self.view addSubview:_rightArrow];

    self.leftArrow.frame = CGRectMake(10, 60, 20, 20);
    [self.view addSubview:_leftArrow];
   
    self.day = [NSDate date];
    
    [self.view addSubview:_dateLabel];
    self.dateLabel.frame = CGRectMake(60, 0, 200, 150);

    self.topBackground.frame = CGRectMake(0, 0, 320, 45);
   [self.view addSubview:_topBackground];
       
   [super viewDidLoad];

}

@end