`

[iOS开发教程-5]Create Indexed UITableView

    博客分类:
  • iOS
 
阅读更多

http://www.iphonedevcentral.com/indexed-uitableview-tutorial/

 

Tackling that handy index on the right side of table views is really not that complicated. In fact, it only requires that you implement two methods. In this tutorial, I’m going to take you step-by-step on how to wire it all together.

Indexed Table 2

 

Prerequisites

If you were able to follow my previous  tutorials , you’re going to be just fine with this one.  I assume that you have  iPhone SDK 3.x   downloaded and installed, know how to create an empty project and files in Xcode and know a thing or two about Objective-C and Cocoa touch. While I am using iPhone SDK 3.2 Beta, I compiled this project against version 3.1.3, which is the current live version.

Let’s get started!

1 .Set up your project

In Xcode, go to  File -> New Project   and choose  Navigation-based Application   from the iPhone OS tab. Name the application  IndexedTable . At this point, you should have a runnable app with an empty table in it.

2. Create a data source

Instead of hardcoding a bunch of values, country names and whatnot, let’s create a simple method that will generate a bunch of strings from the letters of the alphabet so that our UITableView has something to work with.

Create a new class called  DataGenerator . Right-click on the  Classes   group in the project browser and choose  New File . Let the file be an  Objective-C class   (subclass of NSObject) and name it  DataGenerator . This class will only have one static method (for now) that will simply return an array of words from letters. As such, we’ll name it  wordsFromLetters .

In  DataGenerator.h , insert the following code:

@interface DataGenerator : NSObject {
}
 
+ (NSArray *) wordsFromLetters;
 
@end

Now, let’s implement this method. Open  DataGenerator.m   and put this code in it:

@implementation DataGenerator
 
#define WORD_LENGTH 5
 
static NSString *letters = @"abcdefghijklmnopqrstuvwxyz";
 
+ (NSArray *) wordsFromLetters {
    NSMutableArray *content = [NSMutableArray new];
 
    for (int i = 0; i < [letters length]; i++ ) {
        NSMutableDictionary *row = [[[NSMutableDictionary alloc] init] autorelease];
        char currentWord[WORD_LENGTH + 1];
        NSMutableArray *words = [[[NSMutableArray alloc] init] autorelease];
 
        for (int j = 0; j < WORD_LENGTH; j++ ) {
            if (j == 0) {
                currentWord[j] = toupper([letters characterAtIndex:i]);
            }
            else {
                currentWord[j] = [letters characterAtIndex:i];
            }
            currentWord[j+1] = '\0';
            [words addObject:[NSString stringWithCString:currentWord encoding:NSASCIIStringEncoding]];
        }
        char currentLetter[2] = { toupper([letters characterAtIndex:i]), '\0'};
        [row setValue:[NSString stringWithCString:currentLetter encoding:NSASCIIStringEncoding]
               forKey:@"headerTitle"];
        [row setValue:words forKey:@"rowValues"];
        [content addObject:row];
    }
 
    return content;
}
 
@end

 

I’m not going to spend a whole of time explaining what’s going on here because this tutorial is really about adding an index bar to your UITableView. But let’s briefly talk what’s it all about. This method loops through an array letters one-by-one. For each letter it then generates a bunch of words to fill up our content. The final structure of the NSArray we’re returning is going to look something like this:

NSArray =>

  1. NSDictionary
    • headerTitle   => ‘A’
    • rowValues   => {”A”, “Aa”, “Aaa”, “Aaaa”}
  2. NSDictionary
    • headerTitle   => ‘B’
    • rowValues   => {”B”, “Bb”, “Bbb”, “Bbbb”}
  3. etc.

You’ll see how we’re using this array later on. Also note that this list is implicitly ordered.

3. Fill in UITableView with values from  DataGenerator

Next we’re going to populate the currently empty table with data we get from our data generator. Open  RootViewController.h   and add these two instance variables to the class:

#import "DataGenerator.h"
 
@interface RootViewController : UITableViewController {
    NSArray *content;
    NSArray *indices;
}

content   will hold our array of dictionaries while  indices   will hold all initial letters for each word in the list. Let's fill those up. Open  RootViewController.m implementation file and override the method  viewDidLoad   with the following:

- (void)viewDidLoad {
    [super viewDidLoad];
    content = [DataGenerator wordsFromLetters];
    indices = [[content valueForKey:@"headerTitle"] retain];
}

You can see that we're using  [DataGenerator wordsFromLetters]   to simply fill in the  content   variable. The second line of that method returns all keys from the dictionaries in  content   as an array. So  indices   now holds all letters of the alphabet.

We next override the two methods that tell our UITableView how many sections it has and how many rows there are in each section.

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [content count];
}
 
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[[content objectAtIndex:section] objectForKey:@"rowValues"] count] ;
}

The number of sections is equal to the number of letters in our list and the number of rows of each section is equal to the count of each array under its corresponding letter.

Finally, we implement cellForRowAtIndexPath   so that it displays words from our list in the table. We handle headers for sections in  titleForHeaderInSection . This method queries our content at a particular section and demands a  headerTitle   to be returned as header of that section.

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = [[[content objectAtIndex:indexPath.section] objectForKey:@"rowValues"]
                           objectAtIndex:indexPath.row];
 
    return cell;
}
 

You should be able to run your app now (CMD + R) and see something like this:

Indexed Table 01

4. Add index to the table

There is nothing new in what we've done so far. We simply filled in a UITableView with some data. We're now ready to add our index to it. For that, we'll need to implement two methods:  sectionIndexTitlesForTableView   and  sectionForSectionIndexTitle .

Add this code to  RootViewController.m :

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [content valueForKey:@"headerTitle"];
}
 
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [indices indexOfObject:title];
}
 

sectionIndexTitlesForTableView:   In order to properly render the index, the UITableView needs to know all index titles to display. This method returns an array of strings containing all indices. In our case, A, B, C, D, etc.

sectionForSectionIndexTitle:   When you start scrolling through the index, the table needs to know how far down/up to scroll so that the letter you're touching corresponds the appropriate section in the table. This method returns an index value (integer) of the section you're currently touching in the index.

One more thing we need to do before we run our app is to add titles to each section header in UITableView.

- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section {
	return [[content objectAtIndex:section] objectForKey:@"headerTitle"];
 
}

5. Run your app

If everything went well, you should now be able to run your app and see the final product. You'll see the index on the right and scrolling over it will scroll the table appropriately.

indexedtable02

Conclusion

Voilà! That wasn't that hard was it? The main get-away from this tutorial are the two methods you need to implement in order for the index to show up and function properly:  sectionIndexTitlesForTableView : and  sectionForSectionIndexTitle :. In the next tutorial, we'll cover how to add a search bar to this table.

The complete source code for this tutorial can be found here: Indexed UITableView

 

 

分享到:
评论

相关推荐

    STM32+OLED_净水器水流量计源码.rar

    STM32+OLED_净水器水流量计源码.rar

    【机会约束】机会约束优化研究 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    ,,基于EKF的三相PMSM无传感器矢量控制,基于卡尔曼滤波器的无速度传感器 ,核心关键词:基于EKF的三相PMSM无传感器矢量控制; 基于卡尔曼滤波器的无速度传感器 ,基于EKF与卡尔曼滤波器的三相

    ,,基于EKF的三相PMSM无传感器矢量控制,基于卡尔曼滤波器的无速度传感器 ,核心关键词:基于EKF的三相PMSM无传感器矢量控制; 基于卡尔曼滤波器的无速度传感器。,基于EKF与卡尔曼滤波器的三相PMSM无传感器矢量控制研究

    56页-智慧双碳园区建设方案.pdf

    在智慧城市建设的大潮中,智慧园区作为其中的璀璨明珠,正以其独特的魅力引领着产业园区的新一轮变革。想象一下,一个集绿色、高端、智能、创新于一体的未来园区,它不仅融合了科技研发、商业居住、办公文创等多种功能,更通过深度应用信息技术,实现了从传统到智慧的华丽转身。 智慧园区通过“四化”建设——即园区运营精细化、园区体验智能化、园区服务专业化和园区设施信息化,彻底颠覆了传统园区的管理模式。在这里,基础设施的数据收集与分析让管理变得更加主动和高效,从温湿度监控到烟雾报警,从消防水箱液位监测到消防栓防盗水装置,每一处细节都彰显着智能的力量。而远程抄表、空调和变配电的智能化管控,更是在节能降耗的同时,极大地提升了园区的运维效率。更令人兴奋的是,通过智慧监控、人流统计和自动访客系统等高科技手段,园区的安全防范能力得到了质的飞跃,让每一位入驻企业和个人都能享受到“拎包入住”般的便捷与安心。 更令人瞩目的是,智慧园区还构建了集信息服务、企业服务、物业服务于一体的综合服务体系。无论是通过园区门户进行信息查询、投诉反馈,还是享受便捷的电商服务、法律咨询和融资支持,亦或是利用云ERP和云OA系统提升企业的管理水平和运营效率,智慧园区都以其全面、专业、高效的服务,为企业的发展插上了腾飞的翅膀。而这一切的背后,是大数据、云计算、人工智能等前沿技术的深度融合与应用,它们如同智慧的大脑,让园区的管理和服务变得更加聪明、更加贴心。走进智慧园区,就像踏入了一个充满无限可能的未来世界,这里不仅有科技的魅力,更有生活的温度,让人不禁对未来充满了无限的憧憬与期待。

    BST的S变换的批处理研究 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    书房中如何利用镜面增加空间感与光线.doc

    书房中如何利用镜面增加空间感与光线

    电动汽车充电站的最优选址和定容【两种方法】 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    ,,pmsm电阻电感磁链常数辨识源码 电阻,电感,磁链常数辨识 程序在ti dsp实现 在ti开源foc框架基础上开发 能够辨识电机电阻,电感,磁链常数 精度较高,能够满足foc控制需要

    ,,pmsm电阻电感磁链常数辨识源码 电阻,电感,磁链常数辨识。 程序在ti dsp实现。 在ti开源foc框架基础上开发。 能够辨识电机电阻,电感,磁链常数。 精度较高,能够满足foc控制需要。 辨识时间短,大约两秒完成电阻电感辨识。 磁链辨识需要电机旋转。 多次辨识,结果一致性好。 辨识部分代码不包含寄存器操作,易于跨平台移植。 辨识大致原理: 电阻辨识发一个固定的电压矢量,检测电流 电感辨识发一个高频旋转的电压矢量,检测电流,计算感抗。 磁链辨识通过if控制让电机旋转,通过电压电流模型计算转子磁链分量。 ,PMSM; 电阻电感磁链常数辨识; TI DSP实现; TI开源FOC框架; 电机参数辨识; 高精度; 短辨识时间; 跨平台移植; 电阻辨识原理; 电感辨识原理; 磁链辨识原理。,基于TI DSP的PMSM电阻电感磁链常数快速高精度辨识源码

    ,,三菱,FX3U,plc程序模板和触摸屏程序模板,适用于运动轴控制,程序可以在自动的时候暂停进行手动控制,适用于一些中大型设备,可以防止某个气缸超时时,处于自动模式,能够轻松处理,处理完成后,恢复原

    ,,三菱,FX3U,plc程序模板和触摸屏程序模板,适用于运动轴控制,程序可以在自动的时候暂停进行手动控制,适用于一些中大型设备,可以防止某个气缸超时时,处于自动模式,能够轻松处理,处理完成后,恢复原来的气缸,解除暂停即可,思路清晰,编程效率大大提高,程序里附带和仪表的无协议通讯,并且附带最常用的手册。 ,关键词:三菱;FX3U;PLC程序模板;触摸屏程序模板;运动轴控制;自动/手动控制;气缸超时处理;无协议通讯;编程效率;最常用手册。,三菱FX3U PLC程序模板:中大型设备运动轴控制与气缸超时保护

    Matlab实现基于BO贝叶斯优化Transformer结合GRU门控循环单元时间序列预测的详细项目实例(含完整的程序,GUI设计和代码详解)

    内容概要:本文介绍了使用 Matlab 实现基于 BO(贝叶斯优化)的 Transformer 结合 GRU 门控循环单元时间序列预测的具体项目案例。文章首先介绍了时间序列预测的重要性及其现有方法存在的限制,随后深入阐述了该项目的目标、挑战与特色。重点描述了项目中采用的技术手段——结合 Transformer 和 GRU 模型的优点,通过贝叶斯优化进行超参数调整。文中给出了模型的具体实现步骤、代码示例以及完整的项目流程。同时强调了数据预处理、特征提取、窗口化分割、超参数搜索等关键技术点,并讨论了系统的设计部署细节、可视化界面制作等内容。 适合人群:具有一定机器学习基础,尤其是熟悉时间序列预测与深度学习的科研工作者或从业者。 使用场景及目标:适用于金融、医疗、能源等多个行业的高精度时间序列预测。该模型可通过捕捉长时间跨度下的复杂模式,提供更为精准的趋势预判,辅助相关机构作出合理的前瞻规划。 其他说明:此项目还涵盖了从数据采集到模型发布的全流程讲解,以及GUI图形用户界面的设计实现,有助于用户友好性提升和技术应用落地。此外,文档包含了详尽的操作指南和丰富的附录资料,包括完整的程序清单、性能评价指标等,便于读者动手实践。

    分布式光伏储能系统的优化配置方法 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    UQP 启发式方法研究 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    自驾游中的导航技巧提升.doc

    自驾游中的导航技巧提升

    各个操作系统版本的gdal2.4库(包括win32、win64、centos7、centosAarch64、c#、linux32、ubuntu64)

    各个操作系统版本的gdal2.4库(包括win32、win64、centos7、centosAarch64、c#、linux32、ubuntu64)。 GDAL(Geospatial Data Abstraction Library)是一个在X/MIT许可协议下的开源栅格空间数据转换库。以下是对GDAL库的详细介绍: 全称:Geospatial Data Abstraction Library 性质:开源栅格空间数据转换库 用途:进行数据转换和处理 开发语言:C/C++ 数据格式支持:GDAL支持大量的栅格和矢量数据格式,包括常见的地理空间数据格式如GeoTIFF、ESRI Shapefile、GeoJSON、NetCDF、GML等,以及一些专用格式。 数据读取和写入:GDAL可以从不同的数据源中读取地理空间数据,例如文件、数据库、网络服务等,并且可以将数据写入到不同的输出格式。 数据转换和处理:GDAL可以进行各种数据转换和处理操作,包括坐标系转换、重采样、镶嵌、裁剪、投影变换等。此外,它还提供了图像处理和分析功能,如颜色空间转换、直方图均衡化、图像融合、图像代数等。

    漫画作品与人工智能想象.doc

    漫画作品与人工智能想象

    ,,FPGA以SPI模式读写SD卡,已经下板验证通过 可移植到任何FPGA之中 ,核心关键词:FPGA; SPI模式; SD卡读写; 下板验证; 可移植性 ,FPGA SPI模式SD卡读写技术,移

    ,,FPGA以SPI模式读写SD卡,已经下板验证通过。 可移植到任何FPGA之中。 ,核心关键词:FPGA; SPI模式; SD卡读写; 下板验证; 可移植性。,FPGA SPI模式SD卡读写技术,移植通用性极强

    ,,永磁直驱风力发电机并网仿真,机侧采用最大功率跟踪控制,应用尖速比控制和爬山搜索法组合,电机采用单位功率因数控制,进行弱磁控制,网侧采用逆变器并网,跟踪效果理想 多种风力变,同时附赠双馈式风力发电

    ,,永磁直驱风力发电机并网仿真,机侧采用最大功率跟踪控制,应用尖速比控制和爬山搜索法组合,电机采用单位功率因数控制,进行弱磁控制,网侧采用逆变器并网,跟踪效果理想。 多种风力变,同时附赠双馈式风力发电机。 ,永磁直驱风力发电机;并网仿真;最大功率跟踪控制;尖速比控制;爬山搜索法;单位功率因数控制;弱磁控制;逆变器并网;风力变换;双馈式风力发电机。,永磁直驱风力发电:双控策略并网仿真及弱磁双馈式应用

    先休息休息沙发上饭撒的方式

    先休息休息沙发上饭撒的方式

Global site tag (gtag.js) - Google Analytics