Sunday, 2 July 2017

Create PCH file in Xcode 6


In the C and C++ programming languages, a header file is a file whose text may be automatically included in another source file by the C preprocessor, usually specified by the use of compiler directives in the source file.

Prefix.pch is a precompiled header file. Precompiled headers were invented to make compiling faster. Rather than parsing the same header files over and over, these files get parsed once, ahead of time.
Xcode 5 and older version of Xcode by default add PCH file with project, but Xcode 6 doesn't include PCH file automatocally.
We can add PCH file in Project.
Here steps to add PCH file in Project:

1) Create new file by selecting File > New File > iOS > Other > PCH File > Next.
2) Give name to newly created file.(Ex- PrefixHeader)
3) Select Project > Targets > Build Setting.
4) Search for 'Prefix header'.
5) Under "Apple LLVM 7.0" you will get the Prefix Header Key.

 6) Type file directory. (Ex- ProjectFolder/ProjeectName-Prefix.pch).
7) Clean project.
8) Build project.

Monday, 26 June 2017

Circular Progress Bar Indicator

iOS don't provide pre-build 'Circular Progress View/Bar' like UIProgressBar.
Implementing a 'Circular Progress View' is simple in iOS. Here piece of code for implement 'Circular Progress View'.

1) Create a Sub-Class of UIView Class

@interface CircularProgressView : UIView
{
    CGFloat startAngle;
    CGFloat endAngle;
}
@property (nonatomic, assign) CGFloat percentage;
-(id) initWithFrame:(CGRect)frame;
@end

#import "CircularProgressView.h"

@implementation CircularProgressView

-(id) initWithFrame:(CGRect)frame{

  self = [super initWithFrame:frame];
    if (self) {
       
        startAngle = M_PI * 1.5;
        endAngle = startAngle + (M_PI*2);
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor colorWithRed:(CGFloat)235/255 green:(CGFloat)237/255 blue:(CGFloat)236/255 alpha:1] setStroke];
    UIBezierPath *benzierPathBack = [UIBezierPath bezierPath];
    [benzierPathBack addArcWithCenter:CGPointMake(rect.size.width / 2, rect.size.height / 2) radius:(rect.size.width / 2 - 5) startAngle:startAngle endAngle:(endAngle - startAngle) * (100 / 100.0) + startAngle clockwise:YES];
   
    benzierPathBack.lineWidth = 10;
    [benzierPathBack stroke];
   
    CGContextSaveGState(context);
   
    UIBezierPath* bezierPath = [UIBezierPath bezierPath];
   
    // Create our arc, with the correct angles
    [bezierPath addArcWithCenter:CGPointMake(rect.size.width / 2, rect.size.height / 2) radius:(rect.size.width / 2-5) startAngle:startAngle endAngle:(endAngle - startAngle) * (_percentage / 100.0) + startAngle clockwise:YES];
   
    // Set the display for the path, and stroke it
    bezierPath.lineWidth = 10;
    [[UIColor colorWithRed:(CGFloat)1/255 green:(CGFloat)111/255 blue:(CGFloat)37/255 alpha:1] setStroke];
    [bezierPath stroke];  
}


Import CircularProgressView Class, create an object and change percentage value, you can see a 'Circular Progress View'.

Sunday, 18 June 2017

Drawing on View

A UIBezierPath object combines the geometry of a path with attributes that describe the path during rendering. We can set the geometry and attributes separately and can change them independent of one another. Once we have the object configured the way you want it, you can tell it to draw itself in the current context. Because the creation, configuration, and rendering process are all distinct steps, Bezier path objects can be reused easily in  code. We can even use the same object to render the same shape multiple times, perhaps changing the rendering options between successive drawing calls. 
For more details about UIBezierPath Click Here.

Now, we are going to create a simple drawing app using UIBezierpath.

First, create a  subclass of UIView Class.
Suppose name is SketchView
 Inside SketchView.h
@interface SketchView : UIView
{
    UIBezierPath *scriblePath;
}


Add following code in SketchView.m

@implementation SketchView

-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        scriblePath = [[UIBezierPath alloc] init];
        scriblePath.lineCapStyle=kCGLineCapRound;
        scriblePath.miterLimit=0;
        scriblePath.lineWidth = 2; //Set Stroke with
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [[UIColor blackColor] setStroke];
    [scriblePath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}

#pragma mark -
-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     CGPoint touchPoint = [[touches anyObject] locationInView:self.superview];
    [scriblePath moveToPoint:touchPoint];
}
-(void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
     CGPoint touchPoint = [[touches anyObject] locationInView:self.superview];
    [scriblePath addLineToPoint:touchPoint];
    [self setNeedsDisplay];
}

@end

Sunday, 11 June 2017

Custom View With Transparent Oval.

UIBezierPath define a path consisting of straight and curved line segment and render the path in custom views. We can use this for specify the geometry of path, path can define simple shapes such as rectangle, oval, arc or can define complex polygons.For more details about UIBezierPath Click Here.

I am going to draw a custom view with transparent oval.I will use UIBenzierPath  fro achieving result.

First create a SubClass of UIView.
Ex. named sub class to CustomView
Inside drawRect: method of CustomView.m

- (void)drawRect:(CGRect)rect {
    // Drawing code

//First Create path for Oval
    UIBezierPath *apath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5,  self.frame.size.width-10, self.frame.size.height-10)];
    //Create another path
    UIBezierPath *clipPath = [ UIBezierPath bezierPathWithRect:CGRectInfinite];

//Append both path
    [clipPath appendPath:apath];
    clipPath.usesEvenOddFillRule = YES; //

usesEvenOddFillRule property is used to determine whether the even-odd or non-zero rule is used to determine the area enclosed by the path.   

  CGContextSaveGState(UIGraphicsGetCurrentContext());
    [clipPath addClip];
    CGContextSaveGState(UIGraphicsGetCurrentContext());
    [[UIColor orangeColor] setFill];
    [[UIColor blackColor] setStroke];
    clipPath.lineWidth = 2;
    [clipPath stroke];
    [clipPath fill];
}


Sunday, 4 June 2017

Core Animation

Core Animation is a graphics rendering and animation infrastructure use to animate the views and other visual elements. Core Animation is not a replacement for app’s views. Instead, it is a technology that integrates with views to provide better performance and support for animating their content. All you have to do is configure a few animation parameters (such as the start and end points) and tell Core Animation to start. Core Animation does the rest, handing most of the actual drawing work off to the onboard graphics hardware to accelerate the rendering. This automatic graphics acceleration results in high frame rates and smooth animations without burdening the CPU and slowing down your app.

Below code add "Pulse Effect" animation.

//Create a CALayer
CALayer *animatelayer = [CALayer layer];
//Setting Frame for CALayer
animatelayer.frame = CGRectMake(0,0, 160, 160);
//Setting Color for CALayer
animatelayer.backgroundColor = [UIColor redColor].CGColor;
//Setting Position for CALayer
animatelayer.position = (CGPoint){CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds)};
//Setting Corner radius for CALayer to look like a Circle
animatelayer.cornerRadius = 80;

//Create a Basic Animation
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
theAnimation.duration=2.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;theAnimation.fromValue=[NSNumber numberWithFloat:0.7];
theAnimation.toValue=[NSNumber numberWithFloat:0.0];

//Add animation to CALayer
[animatelayer addAnimation:theAnimation forKey:@"animateOpacity"];

//Add CALayer to View
[self.view.layer insertSublayer:animatelayer atIndex:0];

For details Click here

Sunday, 28 May 2017

Frame Animation with CGAffineTransform

One of the most powerful and useful property of UIView is transform, which takes a CGAffineTransform. This is a matrix that express how each pixel of UIView should be modified, applying some mathematical formulas.

CGAffineTransformScale: CGAffineTransformScale use for scale a view up and down. A transform value of 5.0 means make the view 5 times bigger than actual frame.

CGAffineTransformRotate: Use for rotate a view by given angle. It uses radian.


Here a piece of code for render a view  with animation from center.

UIImageView *aniView;

//method for display subview.
-(void) displaySubView{
    //Create object for sub view
    if (!aniView) {
        aniView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.center.y, 0, 0)];
        aniView.backgroundColor = [UIColor clearColor];
        aniView.image = [UIImage imageNamed:@"imagename.png"];
        aniView.clipsToBounds = YES;
        aniView.center = self.view.center;

      // Reduce view to 1/10th of its original frame
        aniView.transform = CGAffineTransformScale(aniView.transform, .01, .01);
        [self.view addSubview:aniView];
    }
    [UIView animateWithDuration:1 animations:^{

        // return the view to original frame
        aniView.transform = CGAffineTransformScale(aniView.transform, 100, 100);
      
    }];
}

//Method for hide subview
-(void) hideSubView{
    [UIView animateWithDuration:1 animations:^{
        aniView.transform = CGAffineTransformScale(aniView.transform, .01, .01);
    }];
}

Sunday, 7 May 2017

UITableView in Swift

Adding a Table View in swift is same as Objective-C.
Create a new Single View Application and give any name you want,  make sure you select 'Swift' language.


 Go to  storyboard and add UITableView, make a IBOutlet for Table view
Now, switch to ViewController .swift class and add UITableViewDelegate and UITableDataSource

Class RolePopOverViewController: UIViewController, UITableViewDelegate,UITableViewDataSource{
  
// IBOutel for UITableView
     @IBOutlet weak var roleTableView: UITableView!  

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
  

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


Note: You can see a error "Type ViewController does not conform to Protocol  ''UITableViewDataSource' ". Its just because we didn't add two required Table View Data Source Method yet.

create a NSArray instance  globally
var allRoleDataArray : NSArray!

Now register UITableViewCell class
roleTableView .registerClass(UITableViewCell.self, forCellReuseIdentifier: "CellIdentifier")
//initialize globally declare array
 allRoleDataArray = ["One","Two","Three","Four","Five"]

Add above lines in viewDidLoad()

Now time to add UITableView Data Source method

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allRoleDataArray.cout  
 }


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       
        let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
        var value : NSString = allRoleDataArray[indexPath.row] as NSString
        cell.textLabel?.text = value
        return cell;
    }


you can't see error any more.
Build and run the app.
Now  open ViewController.swift and add ''didSelectRow'' method

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var value : NSString = allRoleDataArray[indexPath.row] as NSString
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        NSLog("Selected Row = %@", value)
    }


Again run the App and select any row you can see some message on console.
Ex: if you select second row you can see "Selected Row = Two"