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"

Sunday, 30 April 2017

Display Scrollable Image

In some cases image is bigger than screen size.
For display full image within the screen need to bind that image within the UIScrollView.
Process of binding a image with UIScrollview is easy and can achieve in 5 steps.

Here the step by step process to bind a image with UIScrollView.
1)  Create an instant of UIScrollView.
2)  Get image instant to display
3)  Retrieve width and height of image.
4)  Add UIImageView above to UIScrollView.
5)  Set UIScrollview content size equals to image size.

//Add a UIScrollView
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scrollView.backgroundColor = [UIColor whiteColor];
[self.view addSubView:scrollView];

//Get Image
UIImage *displayImage = [UIImage imageNamed:@""];

//Get Image Size
CGSize imageSize = displayImage.size;

//Add Image View
UIImageView *displayImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageSize.width, imageSize.height)];
displayImageView.backgroundColor = [UIColor clearColor];
displayImageView.image = displayImage;
[scrollView addSubView: displayImageView];
[scrollView setContentSize: imageSize];

Sunday, 9 April 2017

Draw a Dashed Pattern Stroke

A small small changes left better impact on UI. In this post we will work on to enhance UI implementation with dashed pattern border on UIView.

Draw dashed pattern border on UIView is very simple and we can use UIBezierPath for draw dashed pattern border.
Lets start, first create subclass of UIView(named DashedBorderView).

#import <UIKit/UIKit.h>

@interface DashedPatternView : UIView

@end


#import "DashedPatternView.h"

@implementation DashedPatternView


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


@end

Go to DashedPatternView.m and uncomment drawRect: method
Now add following code for draw  a rectangle

- (void)drawRect:(CGRect)rect {
    // Drawing code
    [[UIColor blackColor] setStroke];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(10, 10)];
    [path addLineToPoint:CGPointMake(rect.size.width, 10)];
    [path addLineToPoint:CGPointMake(rect.size.width, rect.size.height - 10)];
    [path addLineToPoint:CGPointMake(10, rect.size.height - 10)];
    [path closePath];
    path.lineWidth = 2.0;
    [path stroke];
}

 
Go to your controller class and add DashedPatternView as a subview on main view.
Here code

-(void) addBorderView{
DashedPatternView *dashedView = [[DashedPatternView alloc] init];
    dashedView.frame = CGRectMake(100, 300, self.view.frame.size.width-200, 60);
    dashedView.backgroundColor = [UIColor clearColor];
[self.view addSubview:dashedView];

}

Call addBorderView() method from viewDidLoad() method.
Run the app and you can see a rectangle with solid black border
Now we are going to add dashed pattern border instead of solid border
Add following code just before to call stroke method

CGFloat dashes[] = { 6,6,6};
    [path setLineDash:dashes count:3 phase:0];


above two lines of code enough for draw dashed pattern border.
first we have initialize an array for the dashed border style pattern(you can change the pattern and can see result)
second line of code  set pattern for draw with 3 count(Count of pattern array).

Now run the app and you can see a rectangle with dashed pattern border.


Thursday, 30 March 2017

Get User Current Location

Location service improve the app by enhancing user experience. Lots of application's features base on location service like finding near places, restaurant and whatever user want to search. Uber, Ola, Nearby and tons of applications are based on location service and display required content on the basis of that. Suppose we are stand on a place and want to search restaurant near current location, in this case we must know user current location and than can display result according to user search.
Now question is how can we get user current location? It is not a difficult task, every language provide in build framework and library for perform this task.
 Apple provide Core Location Framework for obtaining all necessary information regarding user's current location. Core Location Framework provide geographic location of device. Click here to know about Geographic coordinate system.

Lets start the coding stuff to fetch current location of a user.
Add Core Location Framework in the build phase of target under"Link Binary with Library"  section, switch to controller class and import location framework and implement <CLLocationManagerDelegate> and declare an instance of CLLocationManager.

#import <CoreLocation/CoreLocation.h>
@interface HomeMapViewController : UIViewController<CLLocationManagerDelegate>{
            CLLocationManager *locationManager;
}
@end

Now switch to .m class and add method for fetch current location

@implementation HomeMapViewController
      - (void)viewDidLoad {
              [super viewDidLoad];
              // Do any additional setup after loading the view from its nib.
               [self  getCurrentLocation];
       }
     -(void) getCurrentLocation{
         locationManager = [[CLLocationManager alloc] init];
         locationManager.delegate = self;
         locationManager.desiredAccuracy = kCLLocationAccuracyBest;
         if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
             [locationManager requestWhenInUseAuthorization];
         }
         [locationManager startUpdatingLocation];
     }
// define delegate methods of <CLLocationManagerDelegate>
      - (void)locationManager:(CLLocationManager *)manager
         didFailWithError:(NSError *)error{
          NSLog(@"Error to fetch location = %@", error);
     }
     -(void) locationManager:(CLLocationManager *)manager didUpdateLocations:               (NSArray<CLLocation *> *)locations{
         CLLocation *location = [locations lastObject];
         CLLocationCoordinate2D cord = location.coordinate;
         NSLog(@"Current Location\n Latitude - %f \n Longitude - %f", cord.latitude, cord.longitude);
     }@end

Now run the app and allow the application to fetch your current location.
You can see latitude and longitude value of location on  console area. We are successfully getting  current location of device/user.
We can stop location update service any time by using 'stopUpdatingLocation' method. It will be better to stop location service after getting current location. add following  line of code inside of 'didUpdateLocations' method

[locationManager stopUpdatingLocation];

But the problem is, value of location in form of latitude and longitude and it is not in human readable address. Lets convert the coordinate value in human readable address.

CLGeocoder class provide service for convert coordinate to human readable address. By specify the latitude and longitude of a given location, you can use CLGeocoder to find a user-readable address.

Lets create a new method for getting human readable address of coordinate.

-(void) getReadableAddressFrom:(CLLocation *)location{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            CLPlacemark *placemark = [placemarks lastObject];
            NSString *address = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",placemark.subThoroughfare, placemark.thoroughfare,placemark.postalCode, placemark.locality,placemark.administrativeArea,placemark.country];
            NSLog(@"Address = %@", address);
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];
}


Inside 'didUpdateLocations' method add line of code to call above method.
[self getReadableAddressFrom:location];

Run the code and check the console, you can see address details.

Note :   For running the application on simulator set the default address of simulator.
In the menu bar, select “Debug” -> “Location” for setting the simulator location.


Sunday, 5 March 2017

Display a controller on the top of all controller

We have in-build methods to present and navigate a new controller from currently visible controller.
We can use "presentViewController: animated: completion:" method to present a new controller and "pushViewController: animated:" method to push a new controller in navigation controller stack.
But for presenting and navigating a new controller  we must know current visible controller, our presenting and navigation code must be inside the current visible controller file. Suppose our project require to display a controller on notification call, when user receive a notification a controller will present. In this scenario we don't know when the app will receive notification, and at the time of receiving  notification, which controller is on top. So what is the best solution of this problem? first option is write  code inside all classes and call this method on the basis of local notification, when a controller appear its add a observer for present a controller and when its disappear remove that observer. But, is this good option/solution? No, its not a solution of problem. If we accept this approach, than we need to add extra work to controller local notification for present and push controller.  Instead of accepting first approach we will find the current visible controller and present new controller from any where of the application and no need to write same code again and again in side all classes.

In this blog post i am going to find current visible controller and present a new controller.
Lets start,

Go to your project and add new category for UIWindow.
Inside .h file add following methods

- (UIViewController *)visibleViewController;
+ (UIViewController *) getVisibleViewControllerFrom:(UIViewController *) vc;


Now switch to .m file and define methods

- (UIViewController *)visibleViewController {
    UIViewController *rootViewController = self.rootViewController;
    return [UIWindow getVisibleViewControllerFrom:rootViewController];
}

+ (UIViewController *) getVisibleViewControllerFrom:(UIViewController *) vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [UIWindow getVisibleViewControllerFrom:[((UINavigationController *) vc) visibleViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [UIWindow getVisibleViewControllerFrom:[((UITabBarController *) vc) selectedViewController]];
    } else {
        if (vc.presentedViewController) {
            return [UIWindow getVisibleViewControllerFrom:vc.presentedViewController];
        } else {
            return vc;
        }
    }

}
 //--------
In the first method, we are not doing any thing, just we are calling the second method with root controller of window.
In the second method,    we are checking the kind of controller(is a kind of UINavigationController, UITabBarController, presentedViewContrller) and returning top of the controller.

Go to ViewController.m file and import UIWindow category class
 and add below method

-(void) displayFullScreenMessage{
//create a instance of controller
    MessageViewController *controller = [[MessageViewController alloc] initWithNibName:@"MessageViewController" bundle:nil];
    //get main window
    UIWindow *mainWindow =  [[UIApplication sharedApplication] keyWindow];

//get current visible controller
    UIViewController *visiblecontroller = [mainWindow visibleViewController];

//present a controller
    [visiblecontroller presentViewController:controller animated:YES completion:nil];
}


Now we have enough code for display a controller on the top of the controller.
Call the above method and display controller.

Friday, 3 February 2017

Draw a curve on UIView

As we all know, User interface is a key part for all application. User interface of an application is only way to interact with end user. A better user interface provide better experiences to end user.
In this block, we are going to create a curve at the upper part of a view.
Resultant screen will be look line below image


                                                                 


For drawing a curve on the upper part of a view, we need to do some math works for setting the radius and center on view. 
We need 3 things for drawing a curve:
1. Center.
2. Radius
3. Start angle.
4. End angle.
At the initial point we are not having any point and angle.
Suppose, we want to draw a curve on the upper part of view with area w * 100, w is the width of view.
now we have 3 points on the curve
1. view x origin and 100.
2. view center and 0.
3. view width and 100.
so all points are:
initial point - (0, 100)
mid point - (w/2, 0)
end point -  (w, 100).

Now we are having three points, so we can draw a triangle using these points
Lets say our triangle is ∆ABC and ø be the angle opposite to side A.
We can calculate distance between all points of triangle AB, BC and CA

Suppose A is the distance between A and B(AB), similarly B is the distance between BC and C is the distance between CA. 
suppose r be the radius of circle/arc.
then A/sinø = 2r,
This isn't hard (just drop a perpendicular from O to A, and use the definition of sin on the similar triangles).

Area of triangle  ∆ABC
K = (BCsinø)/2
sinø = 2K/BC

Now
2r = A/(2K/BC)
r = ABC/4K

Draw a perpendicular for A to BC, we will get height of triangle which is 100(curve draw area as we defined initially)
so K = (base * height) / 2;
K = B * h / 2;

so radius  r = AC / 2h.
we have calculated radius. lets calculate center
x point of center will be in the mid of the curve area and y point will be radius.
so center c = (w/2, r)

now we are ready for draw a curve on the upper part of a view.

Sub-classing of view is the best option for customization and redrawing.
Create a new class(subclass of UIView) namely CurveView(you can choose any name for a class)

in a CurveView.h file declare the following methods and variables
//----variables
    CGFloat radius;
    CGPoint centerPoint;
    CGFloat curveTopMargin;

//----methods
-(instancetype) initWithFrame:(CGRect)frame withUpperCurveMargin:(CGFloat)topMargin;

also declare a macro for convert angle from degree to radians
#define   DEGREES_TO_RADIANS(degrees)  ((M_PI * degrees)/ 180)

Switch to CurveView.m file and following code
//method for initialize an instance of CurveView
-(instancetype) initWithFrame:(CGRect)frame withUpperCurveMargin:(CGFloat)topMargin{
    self = [super initWithFrame: frame];
    if(self){
        curveTopMargin = topMargin;
        [self calculateRadius];
    }
    return self;
}

Now add code for calculate center point and radius
#pragma mark - Calculate radius and center
-(void) calculateRadius{
    CGFloat a = [self calculateDistance:CGPointMake(0, curveTopMargin) andPoint:CGPointMake(self.frame.size.width/2, 0)];
    CGFloat c = [self calculateDistance:CGPointMake(self.frame.size.width, curveTopMargin) andPoint:CGPointMake(self.frame.size.width/2, 0)];
    radius = (a * c)/(2*curveTopMargin);
    centerPoint = CGPointMake(self.frame.size.width/2, radius);
}
-(CGFloat) calculateDistance:(CGPoint)p1 andPoint:(CGPoint)p2{
    CGFloat x =sqrt((pow((p2.x - p1.x), 2)+(pow(p2.y - p1.y, 2))));
    return x;
}


And now add drawRect() method for drawing a view with curve
- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    //-------draw
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor cyanColor].CGColor);
    UIBezierPath *curvePath = [UIBezierPath bezierPath];
    [curvePath addArcWithCenter:centerPoint radius:radius-1  startAngle:DEGREES_TO_RADIANS(0) endAngle:DEGREES_TO_RADIANS(360) clockwise:YES];
    CGPathRef cgPath = CGPathCreateCopy(curvePath.CGPath);
    CGContextAddPath(context, cgPath);
    CGContextSetLineWidth(context, 1);
    CGContextSetShadowWithColor(context, CGSizeMake(0, -1.0), 0.3, [UIColor lightGrayColor].CGColor);
    CGContextDrawPath(context, kCGPathEOFillStroke);
    CGPathRelease(cgPath);
    CGContextRestoreGState(context);
}


Go to controller class and add curve view as a subview
-(void) addCurveView{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CurveView *topCurveView = [[CurveView alloc] initWithFrame:CGRectMake(0, screenSize.height, screenSize.width, 250) withUpperCurveMargin:60];
    topCurveView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:topCurveView];
    CGRect f = topCurveView.frame;
    f.origin.y = screenSize.height - f.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        topCurveView.frame = f;
    }];
}


Run the app, w can see a curve at the upper part.

Click here for Complete project.