Friday, 1 November 2013

Trim White Spaces from NSString

Once i was coding and got stuck over removing spaces from NSString.

To trim preceding, succeeding & white spaces in between  a NSString use below snippet:


    NSString *whitespaceString = @"      This   is  a        string   with       white      spaces         ";
  NSLog(@"String before trimming white spaces: %@", whitespaceString);
  whitespaceString = [whitespaceString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  while ([whitespaceString rangeOfString:@" "].location != NSNotFound)
  whitespaceString = [whitespaceString stringByReplacingOccurrencesOfString:@" " withString:@" "];
  NSLog(@"String after trimming white spaces: %@", whitespaceString);


OR - A better approach using NSPredicate

    NSString *stringWithSpaces = @"      this is    my text  with     lots  of          spaces which is bothering              me";
    NSCharacterSet *spaces = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
    NSArray *arrayOfWordsInTextView =           [[stringWithSpaces componentsSeparatedByCharactersInSet:spaces] 
filteredArrayUsingPredicate:predicate];

    stringWithSpaces = [arrayOfWordsInTextView componentsJoinedByString:@" "];

Thursday, 13 June 2013

iOS 7 Features

Apple has really turned world upside down with its new and awesome iOS 7.
iOS 7 introduces new design, changed icons, upgraded built-in apps and lots of great features.

iOS 7 Features:
1. iTunes Radio.
2. More Smart Siri.
3. Anti Theft Feature - Activation Lock.
4. A Better Notification Center.
5. Control Center.
6. Intelligent Multitasking.
7. Audio-only FaceTime Calls.
8. Inclinometer.
9. Photos and Video Improvement.
10. Airdrop.
11. Enhanced Safari.
12. Improved Apple Maps.


You can find more details about iOS 7:
Link 1
Link 2
Link 3

Wednesday, 17 April 2013

Working with NSMutableAttributedString


Code snippet to demonstrate how to use NSMutableAttributedString:


    UILabel *lblTitle = [[UILabel alloc] init];
    [lblTitle setFrame:CGRectMake(2, 180, 320, 25)];
    [self.view addSubview:lblTitle];
    
    NSString *strHello = @"Hello, this is a Demo of NSMutableAttributedString";
    NSRange range;
    NSMutableAttributedString *stringAttributed = [[NSMutableAttributedString alloc]initWithString:strHello];
    [stringAttributed addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:14.0] range:NSMakeRange(0, [strHello length])];
    range = [strHello rangeOfString:@"NSMutableAttributedString"];
    [stringAttributed addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13.0] range:range];
    range = [strHello rangeOfString:@"Demo"];
    [stringAttributed addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    [lblTitle setAttributedText:stringAttributed];



    Follow link for help: Apple Documentation


Thursday, 4 April 2013

iOS6 Interface Orientation


In iOS6 for interface orientation shouldAutorotateToInterfaceOrientation: method is deprecated.
If you want to make only one controller to orient in all directions but want to restrict a single controller to a specific direction like Portrait then follow:
1. Subclass a UINavigationController and inherit it
2. Override few orientation methods in ViewController in which you want or restrict the orientation support.


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

-(BOOL)shouldAutorotate


-(NSUInteger)supportedInterfaceOrientations



If you want to restrict a ViewController to rotate only in Portrait mode then add code:

#pragma Orientation (override methods)
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}



If you want to allow all orientations on a ViewController then add below code:


#pragma Orientation (override methods)
-(BOOL)shouldAutorotate
{
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}



You can download sample code : Code Here





I followed below link for help:

Wednesday, 3 April 2013

Gradient UIButton

To make a Gradient UIButton follow below code snippet:


    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(90, 120, 140, 32)];
    [btn setTitle:@"Gradient Button" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
    [self.view addSubview:btn];
    
    CAGradientLayer *layer1 = [CAGradientLayer layer];
    NSArray *colors = [NSArray arrayWithObjects:
                       (id)[UIColor lightGrayColor].CGColor,
                       (id)[UIColor blackColor].CGColor,
                       nil];
    [layer1 setColors:colors];
    [layer1 setFrame:btn.bounds];
    [btn.layer insertSublayer:layer1 atIndex:0];
    btn.clipsToBounds = YES;


Final output will look as follows:


NavigationBar Layer Gradient


To add gradient layer to Navigationbar follow below code snippet:


UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    [self.view addSubview:navigationBar];
   // navigationBar.tintColor = [UIColor colorWithRed:.7 green:.5 blue:.2 alpha:1];
    UINavigationItem* item = [[UINavigationItem alloc] initWithTitle:@"Nav Bar"];
    [navigationBar pushNavigationItem:item animated:YES];
    
// Set gradient 
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = CGRectMake(0, 0, 320, 44);
    NSMutableArray *cgColors = [[NSMutableArray alloc] init];
    [cgColors addObject:(id)[[UIColor colorWithRed:1.0
                                             green:0.0
                                              blue:0.0
                                             alpha:0.2] CGColor]];
    [cgColors addObject:(id)[[UIColor colorWithRed:1.0
                                             green:0.0
                                              blue:0.0
                                             alpha:0.6] CGColor]];
    [cgColors addObject:(id)[[UIColor colorWithRed:1.0
                                             green:0.0
                                              blue:0.0
                                             alpha:1.0] CGColor]];
    
    gradient.colors = cgColors;
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 42, 320, 2);
    layer.backgroundColor = [[UIColor colorWithRed:0.0
                                             green:0.0
                                              blue:0.0
                                             alpha:0.7] CGColor];
    [navigationBar setBarStyle:UIBarStyleBlackTranslucent];
    [[[navigationBar.layer sublayers] objectAtIndex:0] insertSublayer:gradient atIndex:0];
    [[[navigationBar.layer sublayers] objectAtIndex:0] insertSublayer:layer atIndex:2];


Final Output will look like:




























I followed stackoverflow : 

Thursday, 7 February 2013

Star Rating in iPhone using UITouch




If you have an application in which you want to take user reviews and want to provide a star rating, you are in a big trouble cause Cocoa Touch (iPhone) does not provide any UIControl for it.
You have to create your own control for this using touch detection or gesture recognition.

In following tutorial i have detected point of touch for achieving my goal.

1. Here i have added a UIView - viewForStarRating on which i placed 5 UIImageViews - imgViewStar1, imgViewStar2, imgViewStar3, imgViewStar4 and imgViewStar5 on my Nib file and set outlet to each.
2. Declare two CGPoints - touchStartPoint and touchCurrentPoint, these CGPoints will give me my touch coordinates.
3. In my implementation file i added touchesBegan and touchesMoved delegate methods.
4. In touchesBegan delegate :
   UITouch *touch = [touches anyObject];
   self.touchStartPoint = [touch locationInView:self.viewForStarRating];
   NSLog(@"Touch detected at: x = %f and y = %f",self.touchStartPoint.x,self.touchStartPoint.y);

5. This self.touchStartPoint.x and self.touchStartPoint.y will give me my initial x & y coordinates of touch in self.viewForStarRating.
6.  In touchesMoved delegate :
        UITouch *touch = [touches anyObject];
    self.touchCurrentPoint = [touch locationInView:self.viewForStarRating];
    
    //NSLog(@"Touch is currently at: x = %f and y = %f",self.touchCurrentPoint.x,self.touchCurrentPoint.y);
    int leftSpace = 20;
    if (self.touchCurrentPoint.x <= leftSpace + 5) {
        [self.imgViewStar1 setImage:[UIImage imageNamed:@"StarEmpty.png"]];
    } else if (self.touchCurrentPoint.x >= leftSpace + 15 && self.touchCurrentPoint.x <= leftSpace + 25) {
        [self.imgViewStar1 setImage:[UIImage imageNamed:@"StarHalf.png"]];
    } else if (self.touchCurrentPoint.x >= leftSpace + 35) {
        [self.imgViewStar1 setImage:[UIImage imageNamed:@"StarFull.png"]];
    }
7. As you can see in above point i have taken a leftSpace which is nothing but the padding space between x coordinate of self.viewForStarRating and self.imgViewStar1.
8. Above code will detect the touch points and will act by changing image in self.imgViewStar1.
9. I just applied a simple logic that if a user slides and leaves touch at initial point (in my case 5 px of self.imgViewStar1), set an empty star image.
10. If user slides till centre (in my case 15 to 25 px of self.imgViewStar1), set a half filled star image.
11. If user slides to end of star (in my case 35px of self.imgViewStar1), set full filled star image.









You can download sample code here: Star Rating

Thursday, 24 January 2013

Methods deprecated in iOS6


In iOS 6 many methods are being deprecated.

1. For UILabel below methods are deprecated.

Deprecated in iOS6:

[self.myLabel setLineBreakMode: UILineBreakModeWordWrap];
[self.myLabel setMinimumFontSize: 14];
[self.myLabel setTextAlignment: UITextAlignmentLeft];


Implementation in iOS6:

[self.myLabel setLineBreakMode: NSLineBreakByWordWrapping];
[self.myLabel setMinimumScaleFactor: 14];
[self.myLabel setTextAlignment:NSTextAlignmentCenter];



2. For presenting and dismissing ModalViewController

Deprecated in iOS6:

[self presentModalViewController:splashViewController animated:NO];
[self dismissModalViewControllerAnimated:YES];

Implementation in iOS6:

[self presentViewController:splashViewController animated:NO completion:nil];
[self dismissViewControllerAnimated:YES completion:nil];