Thursday, 17 December 2015

How to show delete icon on Table View Cell swipe ?

We all find solutions for our problems but the difference is made by the time consumed!!!
Displaying icons on cell swipe is an easy task with this tutorial. Displaying icons on cell swipe is something we always come across while fulfilling clients basic demands. With some easy steps we can do it.
 
So, let's Start. . .
 
1.  Download MGSwipeTableViewCell from this link : https://github.com/MortimerGoro/MGSwipeTableCell
 
2. Drag and drop these files from the downloaded folder
  • MGSwipeButton.h
  • MGSwipeButton.m
  • MGSwipeTableCell.h
  • MGSwipeTableCell.m
  • TestData.h
  • TestData.m

 3. Open the .h file of the custom cell of your table view.
 
4. Import #import "MGSwipeTableCell.h" and change the  class of the cell to "MGSwipeTableCell".
 
5. We are almost done.We need to configure the icons on cell swipe and we are ready to RUN the application.

 Open the .h file of your table view and Import

 #import "MGSwipeTableCell.h"

 and also the delegate method MGSwipeTableCellDelegate.


 Open the .m file of your table view and add this method configuring the number of buttons you seek and the image you want to set.


-(NSArray *) createRightButtons: (int) number
{
    NSMutableArray * result = [NSMutableArray array];
    for (int i = 0; i < number; ++i)
    {
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:nil icon:[UIImage imageNamed:@"trashImg"] backgroundColor:[UIColor whiteColor] callback:^BOOL(MGSwipeTableCell * sender)
                                  {
                                      NSLog(@"Convenience callback received (right).");
                                      BOOL autoHide = i != 0;
                                      return autoHide;         }];
        [result addObject:button];
    }
    return result;


6. Add these delegate methods that will be called when the button is clicked . So add them too.

#if TEST_USE_MG_DELEGATE
-(NSArray*) swipeTableCell:(MGSwipeTableCell*) cell swipeButtonsForDirection:(MGSwipeDirection)direction
             swipeSettings:(MGSwipeSettings*) swipeSettings expansionSettings:(MGSwipeExpansionSettings*) expansionSettings;
{
    TestData * data = [tests objectAtIndex:[_tableView indexPathForCell:cell].row];
    swipeSettings.transition = data.transition;
   
    if (direction == MGSwipeDirectionLeftToRight) {
        expansionSettings.buttonIndex = data.leftExpandableIndex;
        expansionSettings.fillOnTrigger = NO;
        return [self createLeftButtons:data.leftButtonsCount];
    }
    else {
        expansionSettings.buttonIndex = data.rightExpandableIndex;
        expansionSettings.fillOnTrigger = YES;
        return [self createRightButtons:data.rightButtonsCount];
    }
}
#endif



-(BOOL) swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    NSLog(@"Delegate: button tapped, %@ position, index %d, from Expansion: %@",
          direction == MGSwipeDirectionLeftToRight ? @"left" : @"right", (int)index, fromExpansion ? @"YES" : @"NO");
   
    if (direction == MGSwipeDirectionRightToLeft && index == 0) {
        //delete button
        NSIndexPath * path = [autolayoutTableView indexPathForCell:cell];
        return NO; //Don't autohide to improve delete expansion animation
    }
    return YES;
}


7. Add this statement to cellForRowAtIndexPath method:
 
    cell.rightButtons = [self createRightButtons:1];
 
You need to pass the count of the buttons you want to appear on cell swipe. We are all set to RUN the application.
 

 


Apart from this, these methods can also be used to configure the buttons:
 
+(instancetype) buttonWithTitle:(NSString *) title backgroundColor:(UIColor *) color;

+(instancetype) buttonWithTitle:(NSString *) title backgroundColor:(UIColor *) color padding:(NSInteger) padding;

+(instancetype) buttonWithTitle:(NSString *) title backgroundColor:(UIColor *) color insets:(UIEdgeInsets) insets;

+(instancetype) buttonWithTitle:(NSString *) title backgroundColor:(UIColor *) color callback:(MGSwipeButtonCallback) callback;

+(instancetype) buttonWithTitle:(NSString *) title backgroundColor:(UIColor *) color padding:(NSInteger) padding callback:(MGSwipeButtonCallback) callback;

+(instancetype) buttonWithTitle:(NSString *) title backgroundColor:(UIColor *) color insets:(UIEdgeInsets) insets callback:(MGSwipeButtonCallback) callback;

+(instancetype) buttonWithTitle:(NSString *) title icon:(UIImage*) icon backgroundColor:(UIColor *) color;

+(instancetype) buttonWithTitle:(NSString *) title icon:(UIImage*) icon backgroundColor:(UIColor *) color padding:(NSInteger) padding;

+(instancetype) buttonWithTitle:(NSString *) title icon:(UIImage*) icon backgroundColor:(UIColor *) color insets:(UIEdgeInsets) insets;

+(instancetype) buttonWithTitle:(NSString *) title icon:(UIImage*) icon backgroundColor:(UIColor *) color callback:(MGSwipeButtonCallback) callback;

+(instancetype) buttonWithTitle:(NSString *) title icon:(UIImage*) icon backgroundColor:(UIColor *) color padding:(NSInteger) padding callback:(MGSwipeButtonCallback) callback;

+(instancetype) buttonWithTitle:(NSString *) title icon:(UIImage*) icon backgroundColor:(UIColor *) color insets:(UIEdgeInsets) insets callback:(MGSwipeButtonCallback) callback;
 

 


 
 
 
 
 
Hope you will not find any difficulty implementing Buttons on TableViewCell Swipe. 
Feel free to post your suggestions and your contribution to improving this tutorial will be highly appreciated . 
Thanks for visiting and do help your friends to save their time.

Wednesday, 16 December 2015

Auto Layout : Understanding Tricks of Trade Part - III

Auto Layout And Making Watsapp Like Tabs

When its Auto Layout we usually think about those applications that almost every smartphone have like Watsapp. How do they manage to design such complex screens with such perfection!!! Its really  incredible.

 This tutorial will you guide to implement Auto Layout to create Tabs like we find on the top of applications like Watsapp . Nevertheless with growing client demands almost every iOS developer will sooner or later will definitely implement such tabs and with Auto Layout , the task becomes a lot more easier.

So Lets Start....
 This tutorial will use the implemented scroll view from  Auto Layout : Understanding Tricks of Trade Part - I which was very interesting to go along.

1. Drag and drop a View from Object Library on to your XIB and align it as shown below. 


Select the View and click on the Pin button to give Top Edge, Leading Edge and Trailing Edge and Height constraints. Make sure the checkbox against Constraints to Margins is unselected. This gives proper constraints to our base view for tabs.

2. Drag and drop another two views inside this view, of equal widths and height equal to the previously added view.

3. Now select both the Views and click on the Pin button and select the check box against Equal Widths and Equal Heights. Click on the Add 2 Constraints button.


4. Now, select each view individually and give it Top Edge, Leading Edge, Trailing Edge and Bottom Edge constraints. 







5.  Now we are all set to enjoy our work. If you have done everything as per the guidelines then you will observe the below result.
 





Once the Views are properly aligned you can add other objects as you like and continue with the project.

Now lets implement three Tabs...

1. Drag and drop a view next to the above created view. Give it Top Edge, Leading Edge, Trailing Edge and Height constraints. Add three more views in this view of equal width and height equal to the superview.

2. Select all the three views add give it Equal Widths and Equal height from the Pin Menu.


Do not bother about the orange lines as we are not done implementing auto layout.




3. I guess now you are moving with flow, Select each subview individually and give them Top Edge, Leading Edge, Trailing Edge and Bottom Edge constraints. Make sure the check box against Constrint to Margins is left unselected.







4.Now we are all set to see the outcome of our labor . . . Build and Run the application. 






Once our Views get aligned properly, we can add other objects like button to it and add associated functionalities and continue with the project.






Hope you will not find any difficulty implementing Auto Layout. 
Feel free to post your suggestions and your contribution to improving this tutorial will be highly appreciated . 
Thanks for visiting and do help your friends to save their time.

Tuesday, 15 December 2015

Auto Layout : Understanding Tricks of Trade Part - II

Learning Auto Layout With Table View

Getting your constraints right is definitely the hardest and most important part of getting dynamic cell heights and widths working with Auto Layout. If you make a mistake here, it could prevent everything else from working -- so take your time!

This tutorial will guide you to proper implementation of auto layout on table view and its custom cells. So lets start by  making a class for our tutorial.

1. Create a New File and name it as you like (say AutoLayoutTableViewController) and do select the checkbox against XIB.



2. Drag and drop the TableView from object library and connect its DataSource and Delegate to the File's Owner.





3. We can alter the dimensions and selection style of the Table View. Do it if u want to and skipping this will not affect our basic implementation of auto layout.
Select the Table View






4. Lets create the outlet of the table view.



 5. Now we need to give constraints to the table view . We need to understand that we have to give constraints to the any object in such a way that it could automatically adjusts with the changing devices. So we need to properly specify the top edge, leading edge, trailing edge and bottom edge, nevertheless we need to specify the center alignments and some other constraints at times.

Here, for the table view we need to give the Top Edge, Leading Edge, Trailing Edge and Bottom Edge.
Select the Table view and click on the Pin button, located at the bottom of the screen. We will see this kind of pop up.


 6. Click on all the four dotted lines surrounding the square box representing the object to make it solid color representing the selected constraint for the selected object. Make it sure the checbox against Constraint to margins remains unselected. After adding the constraints the pop up should look like this.

 7. We find a button is enabled representing the number of constraints selected. Click on that button to give constraints to the object (Table View).

8. We see that the Table View is surrounded by blue color lines representing that the constraints are properly set. Now we are ready to implement the custom cells on the Table View. Lets start by creating a custom cell of king TableViewCell. Make sure XIB is selected.


9.Adjust the height of Table View Cell as you want to, here we will take it as 60. Do enter the same value of height in the Row Height Column.


10. Now drag and drop a Label from the Object Library in the Cell align as you like.


11. In the same way drag and drop two Image Views in the Cell. Let the cell look like this.


12. Select  the rightmost Image View and click on the Pin button. For this we need to give Top edge, Trailing edge,Height and Width.


13. Select the Image next to the rightmost Image View and give the same constraints as you did for the rightmost image. This will fix the Height and Width and Top edge and trailing edge will be fixed with respect to the rightmost image. So whatever be the cell Width and Right most image and the next to it will look the same as we see here.


14. Select the Label. We need to give the constraints as such that the label's height is fixed along with the top edge leading and trailing edge and the width is variable, that is , the width should get adjusted as per the width of the cell.


15. Do add the Data Source and Delegate Methods of the table view and We are ready to kill the RUN button.


16. Now what if we want to alter the height of the label or any of the image view?? Do we need to remove all the constraints and add it from scratch ??? Is our time and labor got wasted
???
The answer to all these questions is tactfully answered by Apple. So lets see how....

Lets alter the Height of the first Image View and see what happens.


And we find that orange lines start appearing and suggesting that we need to fix this ambiguity of Auto Layout. Don't worry its not a troublesome task to do .

17. Click on the button next to Pin button "Resolve Auto Layout Issues" and click on the Update Constraints button while selecting the disturbed Image View and the magic happens.


Orange lines disappear again and blue lines showing us GREEN to move ahead comes along. So now lets RUN the application and see if we did learn the implementation of Auto Layout on Table View and on its Custom Cell.











Hope you will not find any difficulty implementing Auto Layout. 
Feel free to post your suggestions and your contribution to improving this tutorial will be highly appreciated . 
Thanks for visiting and do help your friends to save their time.


Wednesday, 9 December 2015

Customizing MFSideMenu : A to Z

MFSideMenu utilizes view controller containment and gives you a simple API for implementing side-menu functionality. It integrates with storyboard-based apps as well as traditional setups.

With its versatile and flexible features, it allows us to easily implement it in our projects.
  • Universal device support (iPhone + iPad)
  • Universal orientation support (Portrait + Landscape)
  • Menus on the left and right side of the screen.
  • Storyboard support
  • View controller containment
  • Works with UINavigationController, UITabBarController, and other types of view controllers
  • Nice set of configuration options
  • Lightweight, simple and readable code
    BUT, those who have implemented or sought to implement it might face some difficulties while customizing it. so without giving a lot more with words let's start to :
How To Implement MFSidemenu ?

1. Download the MFSidemenu from https://github.com/mikefrederick/MFSideMenu.

2. Open your project or create a new one for which you want to implement MFSidemenu.
 I have created a  project named SampleProject. Create a  New Group named MFSidemenu.




2. Open MFSidemenu and drag all 7 files from MFSidemenu folder to the newly created folder in your project.






3. Drag SideMenuViewController.h and SideMenuViewController.m file too to your project. Don't worry about the errors , we will resolve them shortly.

4. Import these in your .pch file 

    #import "MFSideMenu.h"
   #import "MFSideMenuContainerViewController.h"
   #import "SideMenuViewController.h" 

5. Import these Frameworks and import them in your .pch

    #import <UIKit/UIKit.h>
    #import <CoreGraphics/CoreGraphics.h>

 TAG: How to add .pch file.

6.  Go to  SideMenuViewController.m. It is always a hectic and cumbersome job to modify someone else' code. So delete entire table view datasource and delegate methods from this class.






7. we will Customize our side menu cells. So create a New File and name it as CustomTableViewCell (say) and do not forget to select the associated XIB




8. We will put a label for time being in the custom cell, implement auto layout to it and our cell is ready to be used in the side menu.





TAG: Auto Layout (Table View): Understanding Tricks of Trade Part - II.

9. We will use this cell as our side menu table view cell. Create a viewDidLoad method in
SideMenuViewController.m and register the cell . Set the data source and delegate .


- (void)viewDidLoad
{
    [super viewDidLoad];

   [self.tableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil]         forCellReuseIdentifier:@"CustomTableViewCell"];
  

     self.tableView.delegate =self;
    self.tableView.dataSource =self;

}


10.  We need to define table view delegate and data source methods.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectio
{
    return 10;//say
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomTableViewCell";
    CustomTableViewCell *cell = (CustomTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    cell.cellTitleLbl.text=[NSString stringWithFormat:@"This Is %ld Row",(long)indexPath.row];
        return cell;
}



11. Our side menu is ready now. But we have not yet decided where to implement this side menu and how ?  

So decide the view controller which will be the center view controller for side menu, and then when that view controller is called we will call the view controller with side menu . CONFUSED !!! 

Don't worry you will be guided through out with examples and snapshots and so you don't face any problem and can help even your friends later.

 Let's say we have a method that calls the center view controller , so instead of simply pushing that view controller use this method to call it with side menu, and you will find that center view controller has got the side menu .

Lets say i have  a button that calls this method 



- (IBAction)OpenSideMenu:(id)sender
{
    CenterViewController *nextViewConollerObj = [[CenterViewController alloc]initWithNibName:@"CenterViewController" bundle:nil];
    SideMenuViewController *leftMenuViewController = [[SideMenuViewController alloc] init];
   
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:nextViewConollerObj];
    MFSideMenuContainerViewController *container = [MFSideMenuContainerViewController
                                                    containerWithCenterViewController:nav
                                                    leftMenuViewController:leftMenuViewController
                                                    rightMenuViewController:nil];
    [[UIApplication sharedApplication] delegate].window.rootViewController = container;
}






12. Create a back button on center view controller , but this back button will not just pop view controller but rather on its click it will open the side menu.




- (IBAction)backButtonClicked:(id)sender
{
    [self.menuContainerViewController toggleLeftSideMenuCompletion:^{
    }];
}


This will open the side menu. Build and RUN the application and if you have done everything the way guided above , the magic happens.





13.  We have not yet implemented the did select of the side menu, so without wasting time ,let's do it. We would be directing only the center view controller but example has been provided how to direct to other view controllers. This saves your time,  so just copy and paste and fasten the development process.

#pragma mark -
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController  *controller;
    if(indexPath.row == 0 )
    {
        CenterViewController *nextViewObj = [[CenterViewController alloc] initWithNibName:@"CenterViewController" bundle:nil];
        controller=nextViewObj;
    }
    else if(indexPath.row == 1)
    {
        CenterViewController *nextViewObj = [[CenterViewController alloc] initWithNibName:@"CenterViewController" bundle:nil];
        controller=nextViewObj;
    }
   else
   {
       CenterViewController *nextViewObj = [[CenterViewController alloc] initWithNibName:@"CenterViewController" bundle:nil];
       controller=nextViewObj;
    }
    UINavigationController *navigationController = self.menuContainerViewController.centerViewController;
    if(controller)
    {
        NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:controller, nil];
        navigationController.viewControllers=array;
    }
    [self.menuContainerViewController setMenuState:MFSideMenuStateClosed];
}


After all these we are set to use side menu, but it still do not look good, and when it is about iPhones it should look not just good but GREAT!!!

Associated classes of MFSidemenu contains so many methods that it is a cumbersome process to find the right method for desired modifications. This tutorial will help you saving your time and will make you appreciate the efforts in your comments.


here the CUSTOMIZATION begins:

1. Starting with very basic that we see ,




The gray color do not goes after selection. Add this statement in didSelectRowAtIndexPath delegate method in SideMenuViewController.m

    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];



2.  We see a black strip at the bottom of the side menu, it does not look good.Does it???
lets remove it.

Go to MFSideMenuContainerViewController.m and find this method 

- (void) setLeftSideMenuFrameToClosedPosition

Add this statement after "leftFrame.origin.y = 0;"

    leftFrame.size.height = self.view.frame.size.height;

 Build and RUN and the gray color and the black color disappears.




3. MFSidemenu has got both right sidemenu and left sidemenu. We can enable both or disable any,
Go to MFSideMenuContainerViewController.m.
 
 Find this method :"- (void)leftMenuWillShow" and change this statement 
" [self.leftMenuViewController view].hidden = NO;" to YES if you want to hide . 


In the same way ,

 Find this method :"- (void)rightMenuWillShow" and change this statement 
" [self.rightMenuViewController view].hidden = NO;" to YES if you want to hide .



4. Now its time to customize the menu width, i.e. when the side menu opens , the width of the center view controller can be adjusted and that too by finding this method 

"- (void)setDefaultSettings" in MFSideMenuContainerViewController.m and 

adding this statement after " self.menuState = MFSideMenuStateClosed;"

    self.menuWidth = self.view.frame.size.width - DESIRED WIDTH; // 55 LOOKS GOOD.




5. Now lets customize the table view background and cell color.
  Go to SideMenuViewController.m

Add this statement in cellForRowAtIndexPath delegate method 
"cell.backgroundColor = [UIColor clearColor];"

 and in  viewDidLoad method

 [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"sidemenuImage.jpg"]]]; 
//IMAGE YOU WANT AS TABLE VIEW BACKGROUND.

BUILD and RUN the application and you will enjoy it this time.





6. You can modify the Lines between Cells, go to viewDidLoad method and add this statement

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;


7. You can modify the scroll indiactor of table view, go to viewDidLoad method and add this statement

    [self.tableView setShowsHorizontalScrollIndicator:NO];
    [self.tableView setShowsVerticalScrollIndicator:NO];

 

 8. You can enable /disable the scrolling of table view, go to viewDidLoad method and add this statement

        self.tableView.scrollEnabled = TRUE;
 


9.  You can enable /disable the pan mode  of side menu, go to viewWillAppear method of the view controller for which you want to disable the pan mode and add this statement

     [self.menuContainerViewController setPanMode:MFSideMenuPanModeNone];



10.  Now the most exciting of all PARALLAX EFFECT 

Find this method in 
 - (void) setCenterViewControllerOffset:(CGFloat)xOffset in MFSideMenuContainerViewController.m


and just replace the method by the below method and avoid the hectic task of modifying it

- (void) setCenterViewControllerOffset:(CGFloat)xOffset {
    CGRect frame = [self.centerViewController view].frame;
    frame.origin.x = xOffset;
    float y=40;
    if(self.menuState == MFSideMenuStateClosed)
    {
        frame.origin.y = y;
        frame.size.height = self.view.frame.size.height - (2*y);

    }
    else
    {
        frame.origin.y = 0;
        frame.size.height = self.view.frame.size.height;
    }
    [self.centerViewController view].frame = frame;
      if(!self.menuSlideAnimationEnabled) return;
       if(xOffset > 0){
        [self alignLeftMenuControllerWithCenterViewController];
        [self setRightSideMenuFrameToClosedPosition];
    } else if(xOffset < 0){
        [self alignRightMenuControllerWithCenterViewController];
        [self setLeftSideMenuFrameToClosedPosition];
    } else {
        [self setLeftSideMenuFrameToClosedPosition];
        [self setRightSideMenuFrameToClosedPosition];
    }
}


Build and RUN the application you will see what you were searching all the way on google. 




11. But why this black patch on top and at down ??? Don't worry we will together remove it or rather hide it .

Add these statements in above method for " MFSideMenuStateClosed"


        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(frame.origin.x, 0, frame.size.width, self.view.frame.size.height)];
        img.image=[UIImage imageNamed:@"sidemenuImage.jpg"];

 //SAME IMAGE USED AS TABLE VIEW BACKGROUND.
  [self.view addSubview:img];
        [self.view sendSubviewToBack:img];




  
Build and RUN the application .

12.  SO black patch is gone but we find that some shadow effect, lets customize it ,

Go to MFSideMenuShadow.m file and find this method "- (void)show" add this statement 

    pathRect.size.height = self.shadowedView.frame.size.height -70 ;


 Build and RUN the application and be ready to see the magic .













Hope you will not find any difficulty implementing MFSidemenu. 
Feel free to post your suggestions and your contribution to improving this tutorial will be highly appreciated . 
Thanks for visiting and do help your friends to save their time.