UITableView:显示有多行数据的一个列。

  新建一个过程:Xcode -> File -> New -> Project...,然后选择iOS -> Application -> Single View Application.

Product Name为HomePwner,其他设置如下所示:

  当使用UITableView的时候,我们必须考虑还需要什么来让这个table能在你的App上工作。

1)一个UITableView一般需要一个视图控制器来处理其在屏幕上显示的样式;

2)一个UITableView需要一个数据源;

3)一个UITableView一般需要一个委托对象,通知其他对象涉及UITableView的事件。委托可以是任何对象,只要其遵守UITableViewDelegate协议。

  UITableViewController类实例满足上述三个角色,即:视图控制器、数据源和委托。当UITableViewController创建了一个UITableView视图时,UITableView的dataSource和delegate实例变量自动设置为指向UITableViewController。其关系如下所示:

  创建一个UITableViewController的子类:

File -> New -> File...,iOS -> Source -> Cocoa Touch Class,点击Next,Class为:BNRItemsViewController,其他设置如下:

  UITableViewController指定的初始化方法为initWithStyle:,我们现在编写BNRItemsViewController指定初始化方法为init,需要1)调用父类的指定初始化方法;2)重载父类的指定初始化方法。

在BNRItemsViewController.m中添加如下代码:

 - (instancetype)init {
self = [super initWithStyle:UITableViewStylePlain];
return self;
} - (instancetype)initWithStyle:(UITableViewStyle)style {
return [self init];
}

  由于不用默认的视图控制器作为根视图控制器,所以修改如下设置:点击工程名Homepwner -> Targets Homepwner -> General -> Deployment Info -> Main Interface 设置为空。

  在BNRItemsViewController.m文件的顶部添加如下代码:

#import "BNRItemsViewController.h"

  修改application:didFinishLaunchingWithOptions:方法如下:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
BNRItemsViewController *itemsViewController = [[BNRItemsViewController alloc] init];
self.window.rootViewController = itemsViewController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}

  添加BNRItem类,File -> New -> File...,iOS -> Source -> Cocoa Touch Class,点击Next,Class为:BNRItem;Subclass of:NSObject。

BNRItem.h的内容如下所示:

 #import <Foundation/Foundation.h>

 @interface BNRItem : NSObject

 @property (nonatomic, copy) NSString *itemName;
@property (nonatomic, copy) NSString *serialNumber;
@property (nonatomic) int valueInDollars;
@property (nonatomic, readonly) NSDate *dateCreated; + (instancetype)randomItem; // Designated initializer for BNRItem
- (instancetype)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber; - (instancetype)initWithItemName:(NSString *)name; @end

BNRItem.m的内容如下所示:

 #import "BNRItem.h"

 @implementation BNRItem

 + (instancetype)randomItem
{
// Create an immutable array of three adjectives
NSArray *randomAdjectiveList = @[@"Fluffy", @"Rusty", @"Shiny"]; // Create an immutable array of three nouns
NSArray *randomNounList = @[@"Bear", @"Spork", @"Mac"]; // Get the index of a random adjective/noun from the lists
// Note: The % operator, called the modulo operator, gives
// you the remainder. So adjectiveIndex is a random number
// from 0 to 2 inclusive.
NSInteger adjectiveIndex = arc4random() % [randomAdjectiveList count];
NSInteger nounIndex = arc4random() % [randomNounList count]; // Note that NSInteger is not an object, but a type definition
// for "long" NSString *randomName = [NSString stringWithFormat:@"%@ %@",
randomAdjectiveList[adjectiveIndex],
randomNounList[nounIndex]]; int randomValue = arc4random() % ; NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'' + arc4random() % ,
'A' + arc4random() % ,
'' + arc4random() % ,
'A' + arc4random() % ,
'' + arc4random() % ]; BNRItem *newItem = [[self alloc] initWithItemName:randomName
valueInDollars:randomValue
serialNumber:randomSerialNumber]; return newItem;
} - (instancetype)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber
{
// Call the superclass's designated initializer
self = [super init]; // Did the superclass's designated initializer succeed?
if (self) {
// Give the instance variables initial values
_itemName = name;
_serialNumber = sNumber;
_valueInDollars = value;
// Set _dateCreated to the current date and time
_dateCreated = [[NSDate alloc] init];
} // Return the address of the newly initialized object
return self;
} - (instancetype)initWithItemName:(NSString *)name
{
return [self initWithItemName:name
valueInDollars:
serialNumber:@""];
} - (instancetype)init
{
return [self initWithItemName:@"Item"];
} - (void)dealloc
{
NSLog(@"Destroyed: %@", self);
} - (NSString *)description
{
NSString *descriptionString =
[[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, recorded on %@",
self.itemName,
self.serialNumber,
self.valueInDollars,
self.dateCreated];
return descriptionString;
} @end

  添加BNRItemStore类,File -> New -> File...,iOS -> Source -> Cocoa Touch Class,点击Next,Class为:BNRItemStore;Subclass of:NSObject。

  BNRItemStore将是一个singleton,意味着在app中,这个类的对象就只有一个。

BNRItemStore.h添加如下代码:

 #import <Foundation/Foundation.h>
@class BNRItem; @interface BNRItemStore : NSObject @property (nonatomic, readonly) NSArray *allItems; + (instancetype)sharedStore;
- (BNRItem *)createItem; @end

BNRItemStore.m添加如下代码:

 #import "BNRItemStore.h"
#import "BNRItem.h" @interface BNRItemStore () @property (nonatomic) NSMutableArray *privateItems; @end @implementation BNRItemStore + (instancetype)sharedStore {
static BNRItemStore *sharedStore = nil;
if (!sharedStore) {
sharedStore = [[self alloc] initPrivate];
}
return sharedStore;
} - (instancetype)init {
@throw [NSException exceptionWithName:@"Singleton"
reason:@"Use+[BNRItemStore sharedStore]" userInfo:nil];
return nil;
} - (instancetype)initPrivate {
self = [super init];
if (self) {
_privateItems = [[NSMutableArray alloc] init];
}
return self;
} - (NSArray *)allItems {
return self.privateItems;
} - (BNRItem *)createItem {
BNRItem *item = [BNRItem randomItem];
[self.privateItems addObject:item];
return item;
} @end

  在sharedStore类方法中声明了一个static变量为sharedStore,当该方法执行完毕的时候,该指针指向的变量不会被销毁。

  返回BNRItemsViewController.m文件,如下,导入BNRItemStore.h和BNRItem.h:

#import "BNRItem.h"
#import "BNRItemStore.h"

  然后,更新指定初始化方法:

 - (instancetype)init {
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
// 添加5个随机item
for (int i = ; i < ; ++i) {
[[BNRItemStore sharedStore] createItem];
}
}
return self;
}

  

  BNRItemsViewController遵守UITableViewwDataSource,必须实现tableView:numberOfRowsInSection:和tableView:cellForRowAtIndexPath:。

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[[BNRItemStore sharedStore] allItems] count];
}
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"
forIndexPath:indexPath];
NSArray *items = [[BNRItemStore sharedStore] allItems];
BNRItem *item = items[indexPath.row];
cell.textLabel.text = [item description];
return cell;
}
 - (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}

  运行程序,结果如下所示:

UITableView 和 UITableViewController的更多相关文章

  1. iOS programming UITableView and UITableViewController

    iOS programming  UITableView and UITableViewController A UITableView displays a single column of dat ...

  2. iOS UITableView 与 UITableViewController

    很多应用都会在界面中使用某种列表控件:用户可以选中.删除或重新排列列表中的项目.这些控件其实都是UITableView 对象,可以用来显示一组对象,例如,用户地址薄中的一组人名.项目地址. UITab ...

  3. UITableView & UITableViewController

    内容概要: 本文先讲解了UITableView概述,然后主要从应用方面讲解了UITableViewController(包括add.delete.move单元cell的操作,以及UITableView ...

  4. UITableView的编辑操作

    继续上篇UITableView和UITableViewController, 打开BNRItemsViewController.m,在类扩展中添加如下属性: @property (nonatomic, ...

  5. iOS--UICollectionView(滚动视图)入门

     UICollectionView @interface UICollectionView : UIScrollView   UICollectionView 和UICollectionViewCon ...

  6. iOS开发知识点总结

    main文件做了这几件事: 1. 创建当前的应用程序 2. 根据4个参数的最后为应用程序设置代理类(默认情况下是AppDelegate) 3. 将appDelegate 和 应用程序 建立关联(指定代 ...

  7. iOS-UICollectionView

    1--------------------------------------------------------------------------------------------------- ...

  8. iOS开发- UICollectionView详解+实例

    本章通过先总体介绍UICollectionView及其常用方法,再结合一个实例,了解如何使用UICollectionView. UICollectionView 和 UICollectionViewC ...

  9. 苹果Xcode帮助文档阅读指南

    文档导读 https://developer.apple.com/legacy/library/navigation/ 前面我们讲Xcode的文档结构是在介绍如何能够快速定位到你要找的内容.但是很多人 ...

随机推荐

  1. recovery 升级前兼容性检查(Vendor Interface Object)

    从android P(9.0)版本开始,我们发现编译出来的OTA升级了里面多了一个文件,compatibility.zip,这个里面存储这system与vendor分区的一些特性,用来做升级前的兼容性 ...

  2. BurpSuit2.0专业版破解

    简介 Burp Suite 是用于攻击web 应用程序的集成平台.它包含了许多Burp工具,这些不同的burp工具通过协同工作,有效的分享信息,支持以某种工具中的信息为基础供另一种工具使用的方式发起攻 ...

  3. 洗礼灵魂,修炼python(67)--爬虫篇—cookielib之爬取需要账户登录验证的网站

    学完前面的教程,相信你已经能爬取大部分的网站信息了,但是当你爬的网站多了,你应该会发现一个新问题,有的网站需要登录账户才能看到更多的信息对吧?那么这种网站怎么爬取呢?这些登录数据就是今天要说的——co ...

  4. Sql Server XML

    实验数据: Create table xmldata (name NVARCHAR(20), age int, sex NVARCHAR(5) ) INSERT INTO xmldata VALUES ...

  5. SqlServer执行Insert命令同时判断目标表中是否存在目标数据

    针对于已查询出数据结果, 且在程序中执行Sql命令, 而非数据库中的存储过程 INSERT INTO TableName (Column1, Column2, Column3, Column4, Co ...

  6. Windows四大傻X功能——那些拖慢系统性能的罪魁祸首

    最近新装了一个PC,配置还算蛮高,i7的CPU,8G内存,2T的硬盘,于是小心翼翼地装了一个干净的正版Win7,但是发现居然开机明显卡?所以做了些研究,发现即使全新安装的正版windows,居然也有些 ...

  7. c/c++ 用前序和中序,或者中序和后序,创建二叉树

    c/c++ 用前序和中序,或者中序和后序,创建二叉树 用前序和中序创建二叉树 //用没有结束标记的char*, clr为前序,lcr为中序来创建树 //前序的第一个字符一定是root节点,然后去中序字 ...

  8. lua时间戳和日期转换及踩坑

    介绍lua的日期函数常用方法及我的一个踩坑. 时间戳转日期 os.date("%Y%m%d%H",unixtime) --os.date("%Y%m%d%H", ...

  9. Can We Make Operating Systems Reliable and Secure?

    Andrew S. Tanenbaum, Jorrit N. Herder, and Herbert Bos Vrije Universiteit, Amsterdam Microkernels-lo ...

  10. js FormData方法介绍

    1. 概述 FormData类型其实是在XMLHttpRequest 2级定义的,它是为序列化表以及创建与表单格式相同的数据(当然是用于XHR传输)提供便利. 2. 构造函数 创建一个formData ...