Monday, 22 October 2012

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)

In some situations we need to add or remove rows dynamically from a UITableView.
We can achieve it very easily, just got through the tutorial :

1. Create a new project.
2.  In AppDelegate implementation file create an object of UINavigationController (navController here).

3. Add object of UIViewController (viewController here) as rootviewcontroller of UINavigationController.
4. In ViewController.xib nib file take a UITableView.
5. Set delegate and datasource of UITableView to File's Owner.
6. Create an IBOutlet to UITableView (tableViewForScreen here) in ViewControler.h header file.

7. Declare an object of NSMutableArray (arrayForTableContent here) in ViewControler.h header file.
8. In ViewController.m file in viewDidLoad method set edit and add buttons as leftBarButtonItem and rightBarButtonItem respectively.
9. Initialize arrayForTableContent array and add objects to it.

10. Now set number of rows, section of UITableView.
11. In cellForRowAtIndexPath set the table cell label.

12. In  'setEditing:(BOOL)editing animated:(BOOL)animated' method set tableview editing and animated.

13. In commitEditingStyle forRowAtIndexPath method:
      If editingStyle is delete remove object from array.
      And using 'deleteRowsAtIndexPaths withRowAnimation'; remove the row at provided index path and with animation style.

14. To insert rows dynamically call insertNewObject method on rightbarbuttonitem.
15. In insertNewObject method add an object to array using 'insertObject atIndex'.
16. And for inserting row to tableview use 'insertRowsAtIndexPaths withRowAnimation' method.

You can download Code
Swift: Swift_Editable_UITableView