How To Delete a Row from UITableView

I hope you have a better understanding about Model-View-Controller. Now let’s move onto the coding part and see how we can delete a row from UITableView. To make thing simple, I’ll use the plain version of Simple Table app as an example.

If you thoroughly understand the MVC model, you probably have some ideas how to implement row deletion. There are three main things we need to do:

1. Write code to switch to edit mode for row deletion
2. Delete the corresponding table data from the model
3. Reload the table view in order to reflect the change of table data

1. Write code to switch to edit mode for row deletion

In iOS app, user normally swipes across a row to initiate the delete button. Recalled that we have adopted the UITableViewDataSource protocol, if you refer to the API doc, there is a method namedtableView:commitEditingStyle:forRowAtIndexPath. When user swipes across a row, the table view will check to see if the method has been implemented. If the method is found, the table view will automatically show the “Delete” button.

Simply add the following code to your table view app and run your app:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{ }

Even the method is empty and doesn’t perform anything, you’ll see the “Delete” button when you swipe across a row.

Swipe to Delete a Table Row

2. Delete the corresponding table data from the model

The next thing is to add code to the method and remove the actual table data. Like other table view methods, it passes the indexPath as parameter that tells you the row number for the deletion. So you can make use of this information and remove the corresponding element from the data array.

In the original code of Simple Table App, we use NSArray to store the table data (which is the model). The problem of NSArray is it’s non-editable. That is, you can’t add/remove its content once the array is initialized. Alternatively, we’ll change the NSArray to NSMutableArray, which adds insertion and deletion operations:

@implementation SimpleTableViewController
{
NSMutableArray *tableData;
} - (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
tableData = [NSMutableArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];
}

In the tableView:commitEditingStyle method, add the following code to remove the actual data from the array. Your method should look like this:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove the row from data model
[tableData removeObjectAtIndex:indexPath.row];
}

The NSMutableArray provides a number of operations for you to manipulate the content of an array. Here we utilize the “removeObjectAtIndex” method to remove a particular item from the array. You can try to run the app and delete a row. Oops! The app doesn’t work as expected.

It’s not a bug. The app does delete the item from the array. The reason why the deleted item still appears is the view hasn’t been refreshed to reflect the update of the data model.

3. Reload the table view

Therefore, once the underlying data is removed, we need to invoke “reloadData” method to request the table View to refresh. Here is the updated code:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove the row from data model
[tableData removeObjectAtIndex:indexPath.row]; // Request table view to reload
[tableView reloadData];
}

iphone dev 入门实例3:Delete a Row from UITableView的更多相关文章

  1. iphone dev 入门实例6:How To Use UIScrollView to Scroll and Zoom and Page

    http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content Getting Starte ...

  2. iphone dev 入门实例7:How to Add Splash Screen in Your iOS App

    http://www.appcoda.com/how-to-add-splash-screen-in-your-ios-app/ What’s Splash Screen? For those who ...

  3. iphone dev 入门实例5:Get the User Location & Address in iPhone App

    Create the Project and Design the Interface First, create a new Xcode project using the Single View ...

  4. iphone dev 入门实例4:CoreData入门

    The iPhone Core Data Example Application The application developed in this chapter will take the for ...

  5. iphone dev 入门实例2:Pass Data Between View Controllers using segue

    Assigning View Controller Class In the first tutorial, we simply create a view controller that serve ...

  6. iphone dev 入门实例1:Use Storyboards to Build Table View

    http://www.appcoda.com/use-storyboards-to-build-navigation-controller-and-table-view/ Creating Navig ...

  7. iphone Dev 开发实例9:Create Grid Layout Using UICollectionView in iOS 6

    In this tutorial, we will build a simple app to display a collection of recipe photos in grid layout ...

  8. iphone Dev 开发实例10:How To Add a Slide-out Sidebar Menu in Your Apps

    Creating the Xcode Project With a basic idea about what we’ll build, let’s move on. You can create t ...

  9. iphone Dev 开发实例8: Parsing an RSS Feed Using NSXMLParser

    From : http://useyourloaf.com/blog/2010/10/16/parsing-an-rss-feed-using-nsxmlparser.html Structure o ...

随机推荐

  1. ASP.NET Web API与Rest web api:发布到IIS(二)(同发布.NET webservice)

    本文档大部分来源于:http://www.cnblogs.com/zqzjs/p/4705994.html 工具VS2010,window环境win7 一:Webservice的创建与方法查看调用 1 ...

  2. 4.2springmvc校验

    1.hibernate的校验框架validation所需要jar包: 2 在applicationContext.xml中配置校验器: <!-- 校验器 --> <bean id=& ...

  3. Vigenère 密码NOIP 2012 提高组 第一天 第一题

    题目描述 16 世纪法国外交家 Blaise de Vigenère 设计了一种多表密码加密算法――Vigenère 密 码.Vigenère 密码的加密解密算法简单易用,且破译难度比较高,曾在美国南 ...

  4. HDU-4521 小明系列问题――小明序列(线段树)

    题目大意:求LIS,但是要求LIS中相邻的两个元素之间的距离要大于d. 题目分析:线段树.节点(l,r)保存信息为LIS的最后一个元素落在[l,r]之间的最大长度.从第d+2个元素开始查询更新操作,但 ...

  5. 移动端动画使用transform提升性能

    在移动端做动画,对性能要求较高而通常的改变margin属性是性能极低的,即使使用绝对定位改变top,left这些属性性能也很差因此应该使用transform来进行动画效果,如transform:tra ...

  6. 黑马程序员——JAVA基础之程序控制流结构之循环结构,循环嵌套

    ------- android培训.java培训.期待与您交流! ---------- 循环结构: 代表语句:while ,do while ,for while语句格式 : while(条件表达式) ...

  7. caffe: compile error: Could not open or find file your path~~/resized_data/0 and a total of 2 images .

    I0219 14:48:40.965386 31108 net.cpp:76] Memory required for data: 0I0219 14:48:40.965517 31108 layer ...

  8. HttpServletRequest/HttpServletResponse乱码问题解决

    1.request.setCharacterEncoding只对POST请求起作用.GET请求用new String(paramterData.getBytes("iso8859-1&quo ...

  9. Linux 下 Lua 与 LuaSQL 模块安装

    相关说明: Lua最近在Nginx的web服务器上挺火的, 它的高效让更多开发喜欢上它, 本文讲述Lua与LuaSQL的安装. 在上几篇mysql-proxy的安装中有提到和操作过. 操作系统: Li ...

  10. 了解oracle数据库的情况

    1.了解你的数据库版本号 2.是否配置了DataGuard? SQL> select protection_mode, protection_level, remote_archive,data ...