- 浏览: 1504506 次
- 性别:
- 来自: 南京
文章分类
- 全部博客 (419)
- XMPP (19)
- Android (180)
- Java (59)
- Network (4)
- HTML5 (13)
- Eclipse (9)
- SCM (23)
- C/C++ (4)
- UML (4)
- Libjingle (15)
- Tools&Softwares (29)
- Linphone (5)
- Linux&UNIX (6)
- Windows (18)
- Google (10)
- MISC (3)
- SIP (6)
- SQLite (5)
- Security (4)
- Opensource (29)
- Online (2)
- 文章 (3)
- MemoryLeak (10)
- Decompile (5)
- Ruby (1)
- Image (1)
- Bat (4)
- TTS&ASR (28)
- Multimedia (1)
- iOS (20)
- Asciiflow - ASCII Flow Diagram Tool.htm (1)
- Networking (1)
- DLNA&UPnP (2)
- Chrome (2)
- CI (1)
- SmartHome (0)
- CloudComputing (1)
- NodeJS (3)
- MachineLearning (2)
最新评论
-
bzhao:
点赞123!
Windows的adb shell中使用vi不乱码方法及AdbPutty -
wahahachuang8:
我觉得这种东西自己开发太麻烦了,就别自己捣鼓了,找个第三方,方 ...
HTML5 WebSocket 技术介绍 -
obehavior:
view.setOnTouchListenerview是什么
[转]android 一直在最前面的浮动窗口效果 -
wutenghua:
[转]android 一直在最前面的浮动窗口效果 -
zee3.lin:
Sorry~~
When I build "call ...
Step by Step about How to Build libjingle 0.4
http://www.iphonedevcentral.com/hello-uitableview/
Hello UITableView!
Ok, let’s start with something really simple. We’ll be creating an app to keep track of your DVD library. The app will have a table view, a detail view and some basic navigational components.
Pre-requisites
I assume you have Xcode and iPhone SDK 3.x already installed (I’m using version Xcode 3.1, with 3.2 being the newest at the time of this writing). I also assume you know how to create a project so I’m not going to cover those little things here. Lastly, I assume you have some knowledge Objective-C , its principles, syntax and paradigms.
1. Set up your project
Create a “Navigation-based Application” and name it “TableViewApp.” Right off the bat, you’ll have an empty app, which is pretty much useless. You can run it using Cmd+R.
2. Create a dummy data set
Right-click on the Resources folder and choose Add -> New File. Under Other category, choose Property List . Name it TestData.plist. This is basically an XML file that will have an empty Dictionary in it by default. Change Dictionary to Array since we’re going to be adding numerous “DVDs” which will be described as individual Dictionaries .
You can add data to it by simply clicking the little button to the right of the Value column. We will be adding information about your DVD collection to it so the schema of your data set could be something like this:
- Title – String
- Cover image – String
- Feature length - Number (in minutes)
- Release date – Date
Of course, this could be extended to more fields such as director, genre, aspect ratio, etc.
Following this schema, add a few items to your dummy data set. You’ll eventually want to have your file looking something like this:
If you don’t feel like typing all this info in, you can download the file here: TestData.plist .
3. Create a DAO (Data Access Object) to access your data
Right-click on the Classes folder and choose Add -> New File . Under Cocoa Touch Class category choose Objective-C class . Name it DvdLibraryDao .
This will be a very simple class that will take our dummy data file, read it in as a NSArray and provide some utility methods to access the data from the file.
First, let’s define our custom init method and some instance variables that will be needed for our implementation.
// Gets a plist name and reads in its contents as an array @interface DvdLibraryDao : NSObject { NSString *libraryPlist; NSArray *libraryContent; } @property (nonatomic, readonly) NSString *libraryPlist; @property (nonatomic, readonly) NSArray *libraryContent; - (id)initWithLibraryName:(NSString *)libraryName; - (NSDictionary *)libraryItemAtIndex:(int)index; - (int)libraryCount; @end
Next we create a custom initialization method, which will give us the name of the property list we want to read in. This code goes in your DvdLibraryDao.m file.
// Gets a plist name and reads in its contents as an array - (id)initWithLibraryName:(NSString *)libraryName { if (self = [super init]) { libraryPlist = libraryName; libraryContent = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:libraryPlist ofType:@"plist"]]; } return self; }
To retrieve information about a particular DVD, we’ll want a method that would access our array at a requested index and then returns the NSDictionary that contains the data we’re after. Add this method to DvdLibraryDao.m.
/ [Safely] returns a "DVD" from the plist. Each item in the data source is a dictionary containing data about // the chosen DVD. - (NSDictionary *)libraryItemAtIndex:(int)index { return (libraryContent != nil && [libraryContent count] > 0 && index < [libraryContent count]) ? [libraryContent objectAtIndex:index] : nil; }
The last method simply returns the count of DVDs in our data file.
// Returns the count of all DVDs in our library - (int)libraryCount { return (libraryContent != nil) ? [libraryContent count] : 0; }
4. Make your Table View read from the DAO
Now that we have a data source, let’s make our table read from it.
Add an instance variable to your RootViewController.h called dao of type DvdLibraryDao.
#import "DvdLibraryDao.h" @interface RootViewController : UITableViewController { DvdLibraryDao *dao; } @end
We’ll initialize this variable in the viewWillAppear method that can be found in the implementation file of RootViewController .
- (void)viewWillAppear:(BOOL)animated { dao = [[DvdLibraryDao alloc] initWithLibraryName:@"TestData"]; }
TestData here is the name of the plist containing our data we created earlier.
To tell our table how many rows it has, we override the delegate method of UITableView called numberOfRowsInSection . All this method does is it returns the number of rows there are in the current section. We’ll cover sections later.
// Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [dao libraryCount]; }
We’re calling the libraryCount method we’ve implemented earlier to get the number of DVDs in our library.
In the last step before we can run this project and see our records in the table, we tell the table what to display at each row. We do this in the delegate method cellForRowAtIndexPath.
// Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"LibraryListingCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"title"]; return cell; }
One note about line #4 that might not be so obvious - static NSString *CellIdentifier = @”LibraryListingCell” . Since tables can potentially have thousands of rows, the system memory consumed by creating all the rows at once would in the best case considerably slow down your table’s performance and in the worst case crash your application.
That’s why Apple introduced the concept of cell reuse. Behind the scenes, the system only creates the visible cells (and some) and as you start scrolling, it reuses the cells that are currently off screen to display the content that is on screen. By giving a cell an identifier, you’re basically marking it to be reused over and over again in your view instead of continuously creating new cells.
5. Add a title to the header
To add a title to the header of the table view, we simply add this line to the viewWillAppear method we overrode earlier.
self.title = @"My DVD Library";
6. See what it looks like so far
Run your project (in the simulator or on the device) and if everything is wired correctly, you should see something like this:
7. Create the Detail View
After a user selects one of the rows, we want them to go to a detail page where more information about the DVD is shown. We could simply use a UIView and add a bunch of UILable s to it to achieve this but since we’re covering UITableView in this tutorial, we’ll create another table.
(Note that this NOT how you’d want do it in a real-life app. I’m showing it strictly to demonstrate a grouped style table.)
Right-click on the Classes folder and choose Add -> New File again. From Cocoa Touch Class category pick the Objective-C class and then choose UITableViewController from the subclass dropdown menu in the lower half of the window. This is different in Xcode 3.1 from previous versions where UITableViewController was simply a part of the presented classes. Name the file DetailViewController.
There are few things we need to do here. We’ll need some place to hold values of the labels used to describe our fields and also the actual values of the fields. For that, let’s create two instance variables of type NSMutableArray which we’ll later fill with appropriate data.
To properly initialize our data in the detail view, we’ll also need a custom init method. It is a modified version of initWithStyle that comes by default with UITableViewController .
@interface DetailViewController : UITableViewController { NSMutableArray *labels; NSMutableArray *values; } - (id)initWithStyle:(UITableViewStyle)style andDvdData:(NSDictionary *)dvdData; @end
Let’s implement our custom init method:
- (id)initWithStyle:(UITableViewStyle)style andDvdData:(NSDictionary *)dvdData { if (self = [super initWithStyle:style]) { labels = [NSMutableArray new]; values = [NSMutableArray new]; // Set up labels which will become header titles [labels addObject:@"Title"]; [labels addObject:@"Release Date"]; [labels addObject:@"Length"]; // Add now the values that correspond to each label [values addObject:[dvdData valueForKey:@"title"]]; // We're faking formatting of date and length here simply dumping them as objects. // We should really convert the values to proper data types and then display them as strings. [values addObject:[NSString stringWithFormat:@"%@", [dvdData valueForKey:@"releaseDate"]]]; [values addObject:[NSString stringWithFormat:@"%@ minutes", [dvdData valueForKey:@"featureLength"]]]; } return self; }
Each table header will display the label of our field (e.g.Title or Release Date). To do that, we’ll override UITableView ’s delegate method titleForHeaderInSection .
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section { return [labels objectAtIndex:section]; }
Now we need to handle header and row counts as well as displaying actual values in our table rows.
The number of headers would correspond to the number of labels we want to display.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [labels count]; }
We’re going to cheat a little bit here. As I mentioned previously, a table view isn’t exactly the best choice to display this kind of data. The reason we’re going to return 1 as number of rows per section is because if we set it to the count of values, we would get duplicate values per each section. Instead of leaving the value as 1 , try setting it to [values count] and see what I mean.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; }
Finally, we set the cell textual value to each corresponding field.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"DetailViewCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text = [values objectAtIndex:indexPath.section]; return cell; }
8. Modify RootViewController to handle DetailViewController
As the last step, we’ll need to tell RootViewController to actually display DetailViewController when a row is pressed. We do that in the didSelectRowAtIndexPath delegate method.
// Override to support row selection in the table view. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // UITableViewStyleGrouped table view style will cause the table have a textured background // and each section will be separated from the other ones. DetailViewController *controller = [[DetailViewController alloc] initWithStyle:UITableViewStyleGrouped andDvdData:[dao libraryItemAtIndex:indexPath.row]]; controller.title = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"title"]; [self.navigationController pushViewController:controller animated:YES]; [controller release]; }
One more detail. When we return back to RootViewController from DetailViewController, we’ll want to deselect the row that had been pressed. To do so, we modify the viewWillAppear method.
- (void)viewWillAppear:(BOOL)animated { dao = [[DvdLibraryDao alloc] initWithLibraryName:@"TestData"]; self.title = @"My DVD Library"; [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES]; }
If everything went well, re-running the project and tapping on one of the rows should show you the detail view table that should look like this:
Conclusion
Hopefully this tutorial has given you a good starting point for creating your own app. The next steps could be replacing the static plist file with a Core Data store or maybe pull the data from a remote XML file. Also, the DetailViewController should really be a subclass of UIView that would provide a lot more flexibility in laying out your data.
You can download a finished version of this project here: My DVD Library Xcode Project .
- MyDVDLibrary01.zip (27.3 KB)
- 下载次数: 2
发表评论
-
Nuance - Dragon Mobile SDK - Speech Kit
2012-07-02 15:57 1415http://dragonmobile.nuancemobil ... -
iOS的开源库和开源项目
2012-06-14 10:54 1027http://www.cocoachina.com/iphon ... -
[iOS开发教程-5]Create Indexed UITableView
2012-06-13 16:31 1743http://www.iphonedevcentral.com ... -
[iOS开发教程-4]Create a UITabBarController from scratch
2012-06-13 15:20 1434http://www.iphonedevcentral.com ... -
[iOS开发教程-3]Create a Detail View Page using UIImageView, UITextView and UILabel
2012-06-13 14:11 2137http://www.iphonedevcentral.com ... -
[iOS开发教程-2]Customize that UIViewCell – Part 1: Using Interface Builder
2012-06-13 13:00 1488http://www.iphonedevcentral.com ... -
Window 7主机与VMware中Mac虚拟机共享文件夹
2012-06-08 23:28 191421. 确保针对Mac虚拟机的VMware Tools的安装 ... -
VMware 8.02虚拟机安装MAC lion 10.7.3教程 附送原版提取镜像InstallESD.iso!
2012-06-08 23:14 6365http://www.winthink.net/thread- ... -
[iOS]深入浅出 iOS 之多线程 NSThread
2012-06-08 15:30 21311http://www.cocoachina.com/bbs/r ... -
Object-C中的Selector概念
2012-06-08 15:25 1103selector可以叫做选择器,其实指的就是对象的方法,也 ... -
CodeBlocks集成Objective-C
2012-06-05 23:35 1194http://www.jxva.com/?act=blog!a ... -
用ultraEdit打造自己的Objective-C IDE for Windows
2012-06-05 21:41 1488http://blog.csdn.net/tomatofly/ ... -
Windows下UltraEdit查看Objective-C代码高亮工具
2012-06-05 21:26 2497http://www.cocoachina.com/bbs/r ... -
Objective-C 编程教程(全)
2012-06-04 23:32 1284http://www.youku.com/playlist_s ... -
iPhone开发学习笔记
2012-06-04 22:15 2685http://blog.csdn.net/huanglx198 ... -
Installing and using GNUstep and Objective-C on Windows
2012-06-04 16:49 1053http://www.techotopia.com/index ... -
GNUStep
2012-06-04 16:45 1246http://www.gnustep.org/ T ... -
Objective C programming in Windows – GNUStep & ProjectCenter
2012-06-04 16:12 1154http://www.jaysonjc.com/program ... -
The Objective-C Programming Language
2012-06-03 19:31 1034http://developer.apple.com/libr ...
相关推荐
- **初识iOS开发**:本节介绍了如何通过创建一个简单的“Hello World”应用程序来开始iOS编程之旅。读者将了解如何安装Xcode并设置项目。 - **编写第一个iOS程序**:指导用户编写第一个iOS应用程序的代码,包括如何...
本书《IOS 5开发教程》是一本经典的iOS开发指南,由Dave Mark、Jack Nutting和Jeff LaMarche共同编写,共有700多页内容。尽管这本书的版本较老(针对的是iOS 5),但它依然包含了开发iOS应用所需的核心概念和技术,...
在iOS开发中,处理UITableView中的行选择是常见的需求,因此教程中也专门有一部分来讲解这一主题。开发者将学习如何通过UITableViewDelegate来处理行选择事件,并编写相应的代码来响应用户的交互。此外,书中还介绍...
1. **Objective-C基础**:Objective-C是iOS开发的主要语言,书中的早期章节会介绍其基本语法、类、对象、消息传递以及内存管理(ARC)等内容。 2. **Xcode工具和Interface Builder**:Xcode是Apple的官方集成开发...
这些知识点都是iOS开发工程师必须掌握的基础技能,通过一步步学习,可以为开发复杂的应用打下坚实的基础。同时,教程也提到了***团队的相关信息,这表明学习资源的提供者可能是一个专注于***/C#/MVC/SQLServer等技术...
第二部分:iOS编程基础:Hello World应用程序如何工作的? 第三部分:iOS 编程向导:创建一个简单的表视图(Table View)应用程序 第四部分:定制UITableView表视图单元格 第五部分:如何处理UITableView中的行选择 ...
第二部分:iOS编程基础:Hello World应用程序如何工作的? 第三部分:iOS 编程向导:创建一个简单的表视图(Table View)应用程序 第四部分:定制UITableView表视图单元格 第五部分:如何处理UITableView中的行选择 ...
总的来说,《Programming iOS 4》是一本全面的iOS开发教程,无论你是初学者还是有经验的开发者,都可以从中受益。通过阅读这本书,你将掌握iOS开发的基本技能,理解iOS应用的工作原理,同时也能了解到如何利用Apple...
- **HelloWorld**:通过创建一个简单的“HelloWorld”应用,初学者可以快速上手,了解Xcode开发环境,熟悉基本的界面设计和代码编写流程。 - **Xcode工作环境**:深入讲解Xcode IDE的使用,包括项目设置、文件管理、...
《Xamarin iOS开发实战上册(内部资料)》是一份专为iOS应用开发者设计的教程,主要关注使用Xamarin框架进行跨平台移动开发的技术。Xamarin是Microsoft旗下的一款强大工具,它允许开发者使用C#语言编写原生的iOS、...
本教程将深入探讨iOS开发中的Objective-C或Swift语言基础,这两种语言都是苹果公司为iOS、macOS和其他平台开发应用的主要工具。 首先,我们来了解一下Objective-C,它是iOS开发早期的主要编程语言。Objective-C是...
本书《一步一步学习 iOS 6 编程(第四版)》是一本面向初学者的iOS开发教程,旨在帮助读者从零基础起步,逐步掌握iOS 6平台下的应用开发。书中涵盖了从基础知识到进阶技术的全面内容,包括Xcode的使用、Objective-C...
《Beginning iOS 14 Programming with Swift》是一本由Appcoda官方提供的原版英文iOS开发教程,适合使用Xcode 12、iOS 14以及Swift 5.3进行学习和开发的人士。本书详细地介绍了iOS应用的开发流程,从基础的Swift编程...
- **UITableView Hello World**:讲解如何创建并展示简单的UITableView,这是iOS应用中常见的数据展示控件。 - **Beginner Interface Builder Hello World**:介绍使用Interface Builder(Xcode中的设计工具)构建...