Tuesday, December 31, 2013

ios7 frame problem.

Getting problem for setting frame for UIButton(Other controls) in ios7. In ios7 view controller using full layout as mentioned in iOS 7 UI Transition Guide (Here ios7 UI Transition Guide). 

if you want change the layout use edgesForExtendedLayout property.


The iOS 7 latest version brings quite a few changes in both design and functionality. As a developer i noticed that apps views would have shifted to the top while porting Apps from iOS6 to iOS7.

In iOS 7 view controllers by default take the full screen layout. Apple designed iOS 7 screens to extend from edge to edge so that the app content is discernible through translucent UI elements. So, this will allows users to view more data on the screen. 

To solve this issue we need to change the edge of the view controller by using the property edgesForExtendedLayout which is available only in iOS7.

 In your UIViewController add
                   self.edgesForExtendedLayout = UIRectEdgeNone;

Make sure to check system version, because edgesForExtendedLayout available in iOS7.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
{
   self.edgesForExtendedLayout = UIRectEdgeNone;
}

Comparing the views after making this change, you’ll notice that your iOS 6 views show up as they were designed. If you are designing your App for iOS 7, highly recommend leveraging the full screen layout that Apple recommends. 

Friday, November 1, 2013

How to create collectionview without storyboard

Since ios5 introduce storyboard is new way to implement the ui interface for the ios. In ios6 new collection view introduce. Today i will show you how to develop collection view without storyboard. UICollectionView is similar to UITableView.

Very similar to table views, collection views brings together a set of cells. Each cell is represented by the UICollectionViewCell class. UICollectionView is a UIkit component which will allow you to develop a grid type of view. Simple and common example of UICollectionView is in photos app where user will allow to scroll number of cell in horizontal or vertical. Collection views support customizable layouts that can be used to implement multi-column grids, tiled layouts, circular layouts, and many more. You can even change the layout of a collection view dynamically if you want.

Let's dive into the real world to achieve this. First create a new project with Empty Application based template(see Figure:1).

Figure : 1

For example i setup my project configuration as below:
  • Product name: KTCollectionView
  • Bundle identifier: com.krunal.collectionview
  • Devices: iPhone
Now add a view controller  with .xib selected in the project. This is the controller where we are developing the our collection view. To build the collection view first add the UICollectionViewDelegate and UICollectionViewDataSource protocols: 

@interface KTViewController: UIViewController<UICollectionViewDelegate, UICollectionViewDataSource>
 Then, drag the collection view in the .xib, and declare the property for collection view.


@property (nonatomic, strong) IBOutlet UICollectionView *collectionView;
Then connect the UICollectionView object in the nib to the outlet. Now connect the UICollectionView object to the datasource and delegate. Select the collection view and go to the Size Inspector and change the cell size 100 x 100 in nib file. (See Figure: 2)



Figure: 2

Now, we will create the custom cell for collection view. For that create a new file of UICollectionViewCell as a selected type. Create .xib also for the new custom cell. Now drag the collection view cell in the UICollectionViewCell's nib file. 


Make the cell size as 100 x 100 in the nib file. After that add an UILabel in the collection view cell.(see Figure: 3) Create a Label property in the .h file and connect in the nib file.


Figure: 3

Now back to the view controller, and update the viewDidLoad method with these lines:

[self.collectionView registerNib:[UINib nibWithNibName:@"KTCell" bundle:nil] forCellWithReuseIdentifier:@"CELL"];
With the view defined, jump over to the implementation of the UICollectionViewDelegate and UICollectionViewDataSource,the numberOfSectionsInCollectionView: andnumberOfItemsInSection: delegate methods. This tells the collection view how many sections are included in the view and how many items are in each section, respectively.


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {                                                                            return 1;                                                                      }
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 100;
}
For example i set the  numberOfSectionsInCollectionView: as value 1, so my collection view have 1 section and for numberOfItemsInSection: as  value 100, so my collection view have 100 cells. Now we need to create one more delegate method  that returns the cells to the collection view as they’re needed. This is the collectionView:cellForItemAtIndexPath method, which is very similar to UITableView's tableView:cellForRowAtIndexPath: method. Add this to the view controller:
- (KTCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KTCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    cell.cellLabel.text = [NSString stringWithFormat:@"cell %i",indexPath.row + 1];
    return cell;
}
I just add the label to display the cell no, you can customize by adding image, multiple label, textview such control for cell. For that you need to add that control to the xib of the cell. Now, we implement the UICollectionViewDelegate method for select the number of cell.

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  KTCell *cell = (KTCell*)[collectionView cellForItemAtIndexPath:indexPath];
  NSArray *views = [cell.contentView subviews];
  UILabel *label = [views objectAtIndex:0];
  NSLog(@"Select %@",label.text);
}
Now, build and run the code you will get your collectionview ready. You will get below output (See Figure: 4)



Figure: 4

You can grab the code from here.

Ref:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionView_class/Reference/Reference.html


Tuesday, October 1, 2013

How to set textView cursor position for last line in ios7?


The actual problem is textview's last line is not visible in ios7 when changing frame of textview, but perfectly visible in ios6. When i was working for project i get this kind of situation and today i will show you how to get rid of this problem. When you change frame of the textview when keyboard is appear, the last line of the textview is below the frame. By changing the shouldChangeTextInRange you will achieve the last line to visible inside the bound of the textview.

// This delegate method is implemented for remove last line hidden

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
       
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
       // ios7
        CGRect textRect = [textView.layoutManager usedRectForTextContainer:textView.textContainer];
        CGFloat sizeAdjustment = (textView.font.lineHeight * [UIScreen mainScreen].scale) + 5;
        
        if (textRect.size.height >= textView.frame.size.height - sizeAdjustment) 
       {
            if ([text isEqualToString:@"\n"]) 
           {
                [textView setContentOffset:CGPointMake(textView.contentOffset.x, textView.contentOffset.y + sizeAdjustment)];
                
            }
        }
    }
    else
    {
       // ios6
        [txtview scrollRangeToVisible:range];
        
        if ([text isEqualToString:@"\n"])
       {  
            [txtview setContentOffset:CGPointMake(txtview.contentOffset.x, txtview.contentOffset.y + 20)];
            
        }
        return YES;
    }
    return YES;
}

Hope, this Solution will save valuable  time for someone.

Saturday, September 21, 2013

How to set custom font in iOS application.

Today i will show you how to set custom font for iOS application. As market grows much people require unique app for their business, fun and for other purpose, so customization is much require for app. Either image, unique UI, Fonts, or any photoshop design.While developing iOS app i also get similar kind of requirement for font customization. 

iOS apps are simply using the “System” font which is the font by default! so i am going to explain the solution for that is to add your custom fonts to your app.Use your existing app's Xcode project or you can create a new Xcode project. 

Follow the below simple steps:

1) Add your font (.TTF) files to your project in XCode  (The files should appear as well in “Target -> Build Phases -> Copy Bundle Resources”).


2) In your “Application-Info.plist” file, add the key “Fonts provided by application” with type “Array”.
3) For each font you want to add to your project, create an item for the array you have created with the full name of the file including its extension (e.g. myfont.ttf).
4) Save your “Application - Info.plist” file.


Usage of Font in App:

Add label in your view controller by simple code, it will display simple default font(Helvetica) in app.

UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(20.0f, 50.0f, 200.0f, 50.0f)];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.text = @"Hello World";
    [self.view addSubview:lbl];

Add below one line code and set the font which you wan't to 

lbl.font = [UIFont fontWithName:@"Fontname" size:20];

UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(20.0f, 50.0f, 200.0f, 50.0f)];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.text = @"Hello World";
    lbl.font = [UIFont fontWithName:@"rayando" size:20];
    [self.view addSubview:lbl];


that's it so simple to add font in app. now, suppose you wan't add change label in IB and wan't to use custom UILabel than what to do. Create Subclass of UILabel type and use of it will gives the solution. Add below code into subclass of the uilabel

Code of .h file 

#import <UIKit/UIKit.h>

@interface KTLabel : UILabel

@end


Code of .m file

#import "KTLabel.h"

@implementation KTLabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


- (id)initWithCoder:(NSCoder *)decoder {
    
    if (self = [super initWithCoder: decoder]) {
        [self setFont: [UIFont fontWithName: @"rayando" size: self.font.pointSize]];
    }
    
    return self;
}


@end


here initWithCoder method of the NSCoder class is used to archive/unarchive of objects.This is a method to write objects on streams (like files, sockets) and being able to retrieve them later or in a different place.

You get custom fonts from  DaFont.(http://www.dafont.com/) and http://www.fontspace.com/



Monday, September 9, 2013

How to install CocoaPods & intro of cocoa pods



CocoaPods is the best way to manage library dependencies in iOS and OS X projects. By using cocoa pods there is no need of downloading the code from github and copying to your project. There are plenty of open source libraries now available with CocoaPods. For get in to deep in cocoa pods you must have prior knowledge of the Xcode and command line Tool.

Why?

When working with third party libraries for iOS and OS X project, its hard to manage it manually. CocoaPods makes managing a project’s dependencies much easier. You only need to specify which dependencies, or pods, you want to include in your project and CocoaPods takes care of the rest.

How to install CocoaPods

Cocoapods runs on Ruby, to install & manage it easily. MAC OS X all version by default installed the Ruby. Before starting make sure you installed command line tool from Xcode preference menu. Refer the below image 1 for Xcode preference menu.


Image 1

Now you need to do is update RubyGems. For that open the Terminal from Launchpad > Utilities > Terminal on MAC. Type the following command in Terminal:

sudo gem update --system

Now, install cocoa pods by typing below command in Terminal

sudo gem install cocoapods
pod setup

Integrating Cocapods with an Xcode project

Create new Xcode project.  (Refer image 2)
Open Xcode -> File -> New -> Project - > Select Single View Application 


Image 2

After creating the project your project structure is look like below image (Refer image3).


Image 3 

Close the Xcode project.  Now we will go for install our first dependency for project. There are so many third party library available  on cocoa pods but for this tutorial we will use SVProgressHUD - A awesome library to create custom activity HUDs for iOS Application, More information about this library you will get here(https://github.com/samvermette/SVProgressHUD).

Now open terminal and change directory to your project directory. Enter below command in terminal:

vi Podfile

The simple editor open in command line add your dependency here. for example:

pod 'SVProgressHUD', '0.9'

A pod is keyword followed by the name  of library. You can add optional version number for library. Here '0.9' indicates the version no , if you left the version number empty CocoaPods will use the latest version available. Now hit the below command in terminal:

pod install

Common Error - Be careful Here.


If you didn't put your Podfile with your .xcodeproj file you will not get success to get the library via pod. Below error you will get (Refer image 4), so make sure your Podfile is with the .xcodeproj file.


Image 4

Upon success of the 'Pod install' you will get below result (Refer image 5).


Image 5

Your project directory structure is look like this (Refer image 6). Here you get the new .xcworkspace file. From now onwards we will use this file to open the project.


Image 6

if you not open the .xcworkspace and you open normal  .xcodeproj file, it will shows you below error on compilation. To avoid it just drag the Pods project into Xcode from your project directory structure. If you directly open the .xcworkspace then no need to drag & add the Pods into Xcode.

open MyCocoapods.xcworkspace to continue and test if it working or not. Thats it you get your third party library for your project. 

Now, suppose your project already contains the pod file and you wan't to add one more third party library in your project then what? Answer is very simple, browse to your pod file in project structure  in terminal. Edit the pod file by hitting vi command in terminal. Add your require dependancies and hit command again in terminal:

pod install

If  your third party library depends on another library, then pods will download and installed that dependent library too. So, thats too handy, no need to worry about dependencies. This make cocoa pods to easy to use for  developer.

Ref: