当前位置:  编程技术>移动开发
本页文章导读:
    ▪UITableView 系列2 :资料的设定方式 (Navigation Controller切换视图) (实例)        UITableView 系列二 :资料的设定方式 (Navigation Controller切换视图) (实例) 这篇文章介绍使用UINavigationController切换视图。这个Navigation Controller功能强大,主要用来切换多级的视图。可以将Navigat.........
    ▪ 相仿 Observer Pattern 的 NSNotificationCenter (实例)        类似 Observer Pattern 的 NSNotificationCenter (实例) NSNotificationCenter 是 Cococa消息中心,统一管理单进程内不同线程的消息通迅,其职责只有两个:    1,提供“观查者们”对感兴趣消息的监听注.........
    ▪ UITableView 系列1 :基本使用方法 (显示,删除,添加图片,添加样式等) (实例)       UITableView 系列一 :基本使用方法 (显示,删除,添加图片,添加样式等) (实例) 基本概念:   1. UITableView 的 Style 预设有两种:Plain 及 Grouped。Plain: Grouped: 2. 装在 UITableView 里面的元素.........

[1]UITableView 系列2 :资料的设定方式 (Navigation Controller切换视图) (实例)
    来源: 互联网  发布时间: 2014-02-18
UITableView 系列二 :资料的设定方式 (Navigation Controller切换视图) (实例)

这篇文章介绍使用UINavigationController切换视图。这个Navigation Controller功能强大,主要用来切换多级的视图。可以将Navigation Controller理解成一个栈,这个栈中可以存放很多View Controller。在这个栈创建的时候,我们先给它添加一个View Controller,称为Root View Controller,它放在栈底,代表的是刚加载程序的时候显示的视图。当用户新选择了一个想要显示的视图时,那个新的View Controller入栈,它所控制的视图就会显示出来。这个新的View Controller通常称作Sub Controller。

 

进入一个新的视图后,左上方会出现一个按钮,叫做Navigation Button,它就像浏览器的后退按钮一样,点击此按钮,当前的View Controller出栈,之前的View就会显示。

 

这种设计模式使得开发变得简单,我们只需知道每一个View Controller的Sub Controller就好了。

我们这次要做的小例子运行如下图:

 

 

左边的图片是刚运行时显示的效果,它是一个表格,表格中的每一行代表不通过的View Controller。注意到每一行的右边有一个图标,叫做Disclosure Indicator,它用来告诉用户单击这一行会进入另一个视图。当点击某行,就进入中间图片显示的视图。中间图片中,左上角的按钮就是Navigation Button。中间的图片中,每一行右边有一个按钮,叫做Detail Disclosure Button,它不仅仅是一个图标,实际上它是一个控件,用户点击它会进入该行的详细说明。点击某行的Detail Disclosure Button,进入相应的视图,如右边的图片。

 

为了更好地理解Navigation Controller的原理,我们从Empty Application开始我们的小例子。

 

1、运行Xcode 4.2,新建一个Empty Application,名称为:Navigation Controller Test:

 

 

2、创建一个View Controller,作为Root View Controller:依次选择File——New——New File,在弹出的窗口,左边选择iOS下的Cocoa Touch,右边选择UIViewController subclass:

 

 

单击Next,在新窗口输入名称为RootViewController,sub of选择UItableViewController:

 

 

之后选好位置,完成创建。

 

3、打开AppDelegate.h,向其中添加属性:

@property (strong, nonatomic) UINavigationController *navController;
 

然后打开AppDelegate.m,在@implementation之前添加代码:

#import "RootViewController.h"
 

在@synthesize window = _window;之后添加代码:

@synthesize navController;

#pragma mark - 
#pragma mark Application lifecycle
 

在didFinishLaunchingWithOptions方法中添加代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    RootViewController *root = [[RootViewController alloc] initWithStyle:UITableViewStylePlain]; 
    self.navController = [[UINavigationController alloc] initWithRootViewController:root]; 
    [self.window addSubview:navController.view];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}
 

4、我们先要明确,Root View Controller中是一个表格,它的每一行对应一个Sub View Controller。

 

打开RootViewController.h,添加属性:

@property (strong, nonatomic) NSArray *controllerList;
 

打开RootViewController.m,在@implementation之后添加代码:

@synthesize controllerList;
 

在viewDidLoad中[super viewDidLoad];之后添加代码:

self.title = @"分类"; 
NSMutableArray *array = [[NSMutableArray alloc] init]; 
self.controllerList = array;
 

在ViewDidUnload方法中添加代码:

self.controllerList = nil;
 

找到numberOfSectionsInTableView方法,修改其返回值为1。

找到numberOfRowsInSection:方法,修改代码为:

return [controllerList count];
 

找到cellForRowAtIndexPath方法,修改其中代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *RootTableViewCell = @"RootTableViewCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: RootTableViewCell]; 
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] 
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier: RootTableViewCell]; 
    } 
    NSUInteger row = [indexPath row]; 
    UITableViewController *controller = [controllerList objectAtIndex:row]; 
    //这里设置每一行显示的文本为所对应的View Controller的标题
    cell.textLabel.text = controller.title;
    //accessoryType就表示每行右边的图标
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    return cell; 
}
 

找到didSelectRowAtIndexPath:方法,修改其中代码如下:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row]; 
    UITableViewController *nextController = [self.controllerList objectAtIndex:row]; 
    [self.navigationController pushViewController:nextController animated:YES]; 
}
 

5、现在为止,我们还看不到什么效果,那是因为controllerList这个数组现在是空的。

接下来我们创建一个Table View Controller,用于显示电影列表。建立的方法同建立RootViewController一样,名称为:MovieViewController。

 

之后再创建一个View Controller,名称为MovieDetailViewController,用于显示电影的详细信息,这次我们要选中include xib file…选项,并且Subof选项为UIViewController:

 

 

6、打开MovieDetailViewController.xib,拖一个Label到中间,并拉长。将其映射到MovieDetailViewController.h中,名称为detailLabel:

 

 

然后在MovieDetailViewController.h中添加属性:

@property (copy, nonatomic) NSString *message;
 

打开MovieDetailViewController.m,在@implementation之后添加代码:

@synthesize message;
 

在viewDidLoad方法后面添加一个方法:

- (void)viewWillAppear:(BOOL)animated { 
    detailLabel.text = message; 
    [super viewWillAppear:animated]; 
}
 

viewWillAppear这个方法每次视图加载都会执行,而viewDidLoad方法只有在第一次加载时才会执行。

 

在viewDidUnload方法中添加代码:

self.detailLabel = nil;
self.message = nil;
 

7、打开MovieViewController.h,向其中添加属性:

@property (strong, nonatomic) NSArray *movieList;
  

打开MovieViewController.m,在@implementation之前添加代码:

#import "MovieDetailViewController.h"
#import "AppDelegate.h"
@interface MovieViewController () 
@property (strong, nonatomic) MovieDetailViewController *childController; 
@end
 

在@implementation之后添加代码:

@synthesize movieList;
@synthesize childController;
 

在viewDidLoad方法中添加代码:

NSArray *array = [[NSArray alloc] initWithObjects:@"肖申克的救赎", @"教父", @"教父:II",
                  @"低俗小说", @"黄金三镖客", @"十二怒汉", @"辛德勒名单",
                  @"蝙蝠侠前传2:黑暗骑士", @"指环王:王者归来", @"飞越疯人院",
                  @"星球大战Ⅴ:帝国反击战", @"搏击俱乐部", @"盗梦空间", @"七武士",
                  @"指环王:护戒使者", @"好家伙", @"星球大战IV:新希望", @"上帝之城",
                  @"卡萨布兰卡", @"黑客帝国", @"西部往事", @"后窗", @"夺宝奇兵",
                  @"沉默的羔羊", @"非常嫌疑犯", @"七宗罪", @"指环王:双塔奇兵", @"阿甘正传",
                  @"惊魂记", @"美好人生", nil];
self.movieList = array;
 

在ViewDidUnload方法中添加代码:

self.movieList = nil;
self.childController = nil;
 

找到numberOfSectionsInTableView方法,修改其返回值为1。

找到numberOfRowsInSection:方法,修改代码为:

return [movieList count];
 

找到cellForRowAtIndexPath方法,修改其中代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MovieTableViewCell = @"MovieTableViewCell"; 
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier: MovieTableViewCell]; 
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] 
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier: MovieTableViewCell]; 
    } 
    NSUInteger row = [indexPath row]; 
    NSString *movieTitle = [movieList objectAtIndex:row];
    //这里设置每一行显示的文本为所对应的View Controller的标题
    cell.textLabel.text = movieTitle;
    //accessoryType就表示每行右边的图标
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; 
    return cell;
}
 

修改didSelectRowAtIndexPath方法:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
}
 

在@end之前添加方法:

- (void)tableView:(UITableView *)tableView
  accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { 
    if (childController == nil) { 
        childController = [[MovieDetailViewController alloc]
                           initWithNibName:@"MovieDetailViewController" bundle:nil]; 
    } 
    NSUInteger row = [indexPath row]; 
    NSString *selectedMovie = [movieList objectAtIndex:row]; 
    NSString *detailMessage = [[NSString alloc]
                               initWithFormat:@"你选择了电影:%@.", selectedMovie]; 
    childController.message = detailMessage; 
    childController.title = selectedMovie; 
    [self.navigationController pushViewController:childController animated:YES]; 
}
  

8、打开RootViewController.m,在@implementation之前添加代码:

#import "MovieViewController.h"
  

在viewDidLoad方法中self.controllerList = array;之前添加代码:

//电影 
MovieViewController *movieViewController = [[MovieViewController alloc]
                                            initWithStyle:UITableViewStylePlain]; 
movieViewController.title = @"电影";  
[array addObject:movieViewController];
 

9、运行一下:

 

 

RootViewController表格中其他选项的实现跟上面是类似的,重复操作比较多,不再讲了。

总的来说,Navigation Controller还是很强大的。使用的时候把它想象成一个栈,用起来就会比较简单。

 

 来源:http://my.oschina.net/plumsoft/blog/52975

 

 

附上: Master-Detail Application 版的代码: StarWars.zip (xcode 4.3)

附上: Empty Application 版的代码 NavigationController-Tableview.zip(xcode 4.3)

 

视频:http://www.youtube.com/watch?v=h72ydCiIwLg&feature=plcp&context=C4da2e12VDvjVQa1PpcFPlH7OSz8KtLBvah_bDxdE86kasYQU9OuI%3D

 

 

 

 

1 楼 babywzazy 2012-05-29  
为什么我New File的时候没有UIViewController subclass这个选项呢。。。步骤都是正确的啊。。。左边ios的cocoa touch里面没有,其他地方找了一下也没看到
2 楼 天梯梦 2012-05-29  
babywzazy 写道
为什么我New File的时候没有UIViewController subclass这个选项呢。。。步骤都是正确的啊。。。左边ios的cocoa touch里面没有,其他地方找了一下也没看到


请问你用的是什么版本的xcode? 我用的是4.3

    
[2] 相仿 Observer Pattern 的 NSNotificationCenter (实例)
    来源: 互联网  发布时间: 2014-02-18
类似 Observer Pattern 的 NSNotificationCenter (实例)

NSNotificationCenter 是 Cococa消息中心,统一管理单进程内不同线程的消息通迅,其职责只有两个:

 

 1,提供“观查者们”对感兴趣消息的监听注册

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(printName:) name: @"messageName" object:nil];
 

 a, defaultCenter,消息中心只有一个,通过类方法获取它的单例。

 b, addObserver,添加监听者实例,此处为当前实例

 c, selector,observer中的一个方法指针,当有消息的时候会执行此方法,并把相关上下文以参数传递过去

 d, name,注册所关心消息的名称,

 e, object,这个是对消息发送方的一个过滤,此参数据说明当前监听器仅对某个对象发出的消息感兴趣。

 

 整体意思:

 向消息中心中注册一个“监听者”(当前实例self, 相当于Java里的this)。当有名为NSWindowDidBecomeMainNotification 的消息发送到消息中心时,执行本实例的aWindowBecameMain方法。

 

 2,接收“消息”,并把消息发送给关心它的“观查者们”。

 

 消息的推送:

 [[NSNotificationCenter defaultCenter] postNotificationName:@"messageName" object:nil userInfo: [NSDictionary dictionaryWithObject:@"jory" forKey:@"name"|^Archive.zip]];
 

 a, postNotificationName,推送消息的名称,匹配在注册消息监听者时的消息名称。

 b, object, 发送消息的实例

 c, userInfo,发送消息时附带的消息上下文,此实例为一个字典实例(相当于Java里的HashMap)。

 

 3,当有消息推送到消息中心后,会把此消息发送给相关的“监听者”,并会执行消息注册时的方法:

 -(void)printName:(id)sender{
 NSString *name = [[sender userInfo] objectForKey:@"name"];
 NSLog(@"name: %@",name);
 }
 

 方法很简单,从消息上下文中(发送消息时的 userInfo),获取"name"并打印。

 

 以下是一个完整的消息分发工程,

 特意把事件注册与推送写到两个类中(从头文件中可以发现两个类并没有直接的引用)

 

 项目:Archive.zip

 

 主要代码如下

 

 notificationTestAppDelegate中:

 //在消息中心中注册消息
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickBtn:) name:@"clickBtn" object:nil];
 

 TestView中:

 //向消息中心推荐送名为"clickBtn"的消息
 [[NSNotificationCenter defaultCenter] postNotificationName:@"clickBtn"
 object:nil userInfo:[NSDictionary dictionaryWithObject:@"jory" forKey:@"name"]];
 

来源:http://wiki.magiche.net/pages/viewpage.action?pageId=1540216#NSNotificationCenter%E4%B8%8E%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%28Observer%29-NSNotificationCenter

 

在 Design Patterns 中的 Observer Pattern 主要目是用来解决一对多的物件之间的依附关系,只要物件状态一有变动,就可以通知其他相依物件做跟更新的动作,举个简单的例子 Observer 就像是一个班级里负责联络的窗口一样,当班级内有人有讯息需要通知给所有人时,只要告诉这个联络窗口,之后就由联络窗口统一通知班级内的所有人,当然也包含发佈消息的这个人。在 Objective-C 里我们并不需要真的去实作出 Observer Pattern,透过使用 NSNotificationCenter 也可以达到相同的效果。

 

 NSNotificationCenter 可以分成三部份来看,分别是註册(订阅)ˋ註销(取消订阅)与讯息通知。

 

 在订阅的部份,物件必须向 NSNotificationCenter 进行註册,并且说明想要订阅的讯息事件,和设定收到通知时要执行的函式,通常我们可以将订阅的部份直接写在物件初始化的地方,这样物件在建立之后就可以立刻向 NSNotificationCenter 订阅他所需要的资讯

- (id)init {
 self = [super init];
 if (self) {

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(echoNotification:) name:@"showSomething" object:nil];
 }

 return self;
 }
 

上述程式码在完成初始化之后随即向 NSNotificationCenter 订阅关于 showSomething 的讯息事件,可以解释成日后只要有 NSNotificationCenter 发佈有关 showSomething 讯息事件的通知,此物件就会执行 echoNotification: 函式,而此物件内的 echoNotification: 函式如下。

- (void)echoNotification:(NSNotification *)notification {

 //取得由NSNotificationCenter送来的讯息
 NSArray *anyArray = [notification object];

 NSLog(@"%@", [anyArray componentsJoinedByString:@"\n"]);
 }
 

由 NSNotificationCenter 送来的讯息可以是任何形态,在这里假定订阅的 showSomething 讯息事件只会送来 NSArray 形态的参数。

 

 在取消订阅的部份,可以参考下列程式码来註销该物件对 NSNotificationCenter 订阅的所有讯息事件。

 [[NSNotificationCenter defaultCenter] removeObserver:self];
 

 或是使用下列程式码对特定的讯息事件取消订阅(同一个物件可以同时订阅数种不同的讯息事件)。

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"showSomething" object:nil];
 

  最后是讯息通知的部份,其程式码如下。

 [[NSNotificationCenter defaultCenter] postNotificationName:@"showSomething" object:stringArray];
 

 执行上述程式码,NSNotificationCenter 将会通知所有订阅 showSomething 讯息事件的物件,并附带讯息内容(stringArray 参数)。

 

 

来源: http://furnacedigital.blogspot.com/2011/09/observer-pattern-nsnotificationcenter.html

 

 


    
[3] UITableView 系列1 :基本使用方法 (显示,删除,添加图片,添加样式等) (实例)
    来源: 互联网  发布时间: 2014-02-18
UITableView 系列一 :基本使用方法 (显示,删除,添加图片,添加样式等) (实例)

基本概念:

 

1. UITableView 的 Style 预设有两种:Plain 及 Grouped。

Plain:
 

Grouped:
 

2. 装在 UITableView 里面的元素是 UITableViewCell。

Cell的结构图:
 

3. 而 UITableViewCell 预设有4种样式 Style:

UITableViewCellStyleDefault:预设使用这种,若左侧ImageView没图的话,只有一行字(textLable.text)。
 

UITableViewCellStyleValue1:左侧为textLable.text并且左对齐,右侧为detailTextLable.text并且右对齐。
 

UITableViewCellStyleValue2:左侧为detailTextLable.text,右侧为textLable.text并且左对齐。
 

UITableViewCellStyleSubtitle:跟UITableViewCellStyleDefault大致相同,detailTextLable.text出现在textLable.text下方。
 

textLable和detailTextLable都包含在contentView里面。

 

来源:http://skyx.wordpress.com/2012/01/09/ios-uitableview-use-and-summary/

 

UITableView 基本使用方法 (一) - 如何顯示資料

 

UITableView 是 iOS 中,非常重要的使用者介面 ,仔细观察 iOS App 中,除了游戏类的 App 以外,几乎都会用上 UITableview, 因为使用 UITableView 的目的就是要呈现数十笔甚至上百笔的资料给使用者,透过 UITableView ,使用者可以透过捲动画面,来获得或是查询想要的资料,本文将介绍 UITableView 的基本使用方法。

 

 在 Xcode 中,开启一个 Single View Application, Device Family 为iPhone,取消 “Use Storyboard” 和 "Include Unit Tests".

 

在xib文件中,拖入 Table View,并且使 Outlets 下的 dataSource 和 delegate 与 File's Owner相连。

 

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    NSArray *items;
}

@property (nonatomic,retain) NSArray *items;

@end

 

ViewController.m

@synthesize items;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    // Set up the NSArray
    self.items = [[NSArray alloc] initWithObjects:@"Item 1",@"Item 2",@"Item 3", @"Item 4",@"Item 5",@"Item 6",@"Item 7",@"Item 8",@"Item 9",@"Item 10",@"Item 11",@"Item 12", nil];
}

#pragma mark - TableView Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.items count]; // or self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Step 1: Check to see if we can reuse a cell from a row that has just rolled off the screen
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    // Step 2: If there are no cells to reuse, create a new one
    if(cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    // Add a detail view accessory
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    
    // Step 3: Set the cell text
    cell.textLabel.text = [items objectAtIndex:indexPath.row];
    
    // Step 4: Return the cell
    return cell;
}

 

或者添加图片

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Step 1: Check to see if we can reuse a cell from a row that has just rolled off the screen
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    // Step 2: If there are no cells to reuse, create a new one
    if(cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    // Add a detail view accessory
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    
    // Step 3: Set the cell text
    cell.textLabel.text = [items objectAtIndex:indexPath.row];

    //每一行row進來都判定一下,分別依次選用不同的圖片
    switch (indexPath.row) 
    {
        case 0:
            cell.imageView.image = [UIImage imageNamed:@"image0.png"];
        break;
           
        case 1:
            cell.imageView.image = [UIImage imageNamed:@"image1.png"];
        break;
        
        case 2:
            cell.imageView.image = [UIImage imageNamed:@"image2.png"];
        break;
            
        default:
            cell.imageView.image = [UIImage imageNamed:@"common.png"];
        break;
    }

    //設字體、顏色、背景色什麼的
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor colorWithRed:54.0/255.0 green:161.0/255.0 blue:219.0/255.0 alpha:1];
    cell.detailTextLabel.textColor = [UIColor colorWithRed:135.0/255.0 green:135.0/255.0 blue:135.0/255.0 alpha:1];
    
    //設定textLabel的最大允許行數,超過的話會在尾未以...表示
    cell.textLabel.numberOfLines = 2;

    // Step 4: Return the cell
    return cell;
}
 

视频: http://www.youtube.com/watch?v=sTM7nxup_xc&feature=related

 

解释如下:

 

要设定 UITableView 欲显示资料的部份,首先找到 numberOfSectionsInTableView: 方法。在此方法中,需要设定将会呈现多少个 section,也就是对 UITableView 做分类,在此实作中,没有需要用到两个以上的分类,因此我们设定回传值为 1 ,完整的方法设定如下:

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
 return 1;
 }
 

 再来设定有多少列要显示在 UITableView 上面,在 tableView: numberOfRowsInSection: 方法中,我们告知 UITableView 将有多少笔资料要显示给使用者,完整方法设定如下:

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

 //阵列中所包含的物件个数,即为要显示的资料数量,也就是多少列
 return [self.tableViewArray count];
 }
 

 最后在 UITableView 当中,我们要告知每一个 UITableViewCell 需要输出什么样的资料,在此范例中,我们是以字串做为资料的显示,因此我们将 tableViewArray 中的每一个字串指定给每一列,在 tableView: cellForRowAtIndexPath:方法中,我们输入以下程式码:

 // 设定以下字串的用意是设定一个标籤,来进行重复使用 UITableViewCell 的工作 
 static NSString *CellIdentifier = @"Cell";

 //询问 tableView 是否有可以重复利用的 UITableViewCell
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

 //若无则产生一个新的 UITableViewCell
 if (cell == nil) {

 //产生 UITableViewCell 的同时,设定 UITableViewCell 的形态,并且赋予标籤,以利重复使用 UITableViewCell
 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
 }

 //设定 UITableViewCell 中 textLable 的文字,根据 indexPath.row 来给定在 tableViewArray 中的字串
 cell.textLabel.text = [self.tableViewArray objectAtIndex:indexPath.row];

 return cell;
 

 上列方法中,由于 UITableView 一次包含数十个 UITableViewCell, 并且进行上下捲动,当 UITableViewCell 数量有上百笔的时候,不可能一次产生数百个 UITableViewCell 加入到 UITableView 当中,因此 Apple 使用了可以重复利用 UITableViewCell 的机制,赋予 UITableViewCell 可以重复使用的标籤,当 UITableViewCell 因捲动而不在画面上的时候,就会先呼叫 UITableView 有无可以重复使用的 UITableViewCell,这样可以节省记忆体的使用量。

 

以上完成后,即可显示出 UITableView 并显示阵列中的字串在每一个 UITableViewCell 上。最后必须要说明的是,使用 UITableViewController 时,其 tableViewController.view 所回传的物件并非 UIView 而是 UITableView,因为在 XIB 档中,File's Owner 的 view outlet 是与 UITableView 相连接的。

 

UITableView 基本使用法 (二) - 删除资料列

 

 在上一篇 UITableView 基本使用法 (一) 中,我们介绍了如何让 UITableView 呈现我们需要的资料,在接下来的文章中,将介绍如何删除资料列。

 

 在介绍如何删除资料列之前,应该先回顾一下 MVC design pattern, 也就是 Model - View - Controller 的设计样式。UITableView 也是遵循这样的 design pattern, 在 UITableView 基本使用法 (一) 中,我们使用阵列也就是我们的 Model 来存放字串资料,然后透过 UITableViewController 来变更 UITableView 的显示内容,同样地,在删除 UITableView 中的资料列时,也代表着我们将阵列中的资料删除,倘若我们不变更阵列的内容,也就是我们不对阵列进行物件的删除,然后直接要求 UITableView 进行显示资料的删除时,得到的结果就是 crash!因此,进行资料列的删除首要是先对 Model 也就是阵列内容进行删除,然后再执行 UITableView 的显示资料删除,而进行 Model 以及 View 内容变更的正是 UITableViewController, 如此符合 MVC 的精神。

 

 回归正题,依据之前的 UITableView 基本使用法 (一) Xcode 专案,回到 UITableViewController subclass, 原本在 viewDidLoad 中,我们使用 NSArray 来产生阵列,但是 NSArray 无法进行物件的新增与删除,因此,必须将 阵列重新宣告为 NSMutableArray, 因为我们将利用 NSMutableArray 中的 removeObjectAtIndex: 方法来移除物件。在 viewDidLoad 中重新设定阵列的宣告,程式码如下:

 

.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    NSMutableArray *items;
}

@property (nonatomic,retain) NSMutableArray *items;

@end
 
@synthesize items;
 - (void)viewDidLoad {
 [super viewDidLoad];

 //设定包含六个 NSString 字串的阵列
 self.items = [[NSMutableArray alloc] initWithObjects:@"First", @"Second", @"Third",@"Fourth",@"Five",@"Six",nil];
 }
 

 再来置入以下方法,此方法为设定是否 UITableView 能否被进行编辑,在此方法中回传 YES , 代表 UITableView 起始删除功能。

 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 

 当我们起始删除功能之后,就可以利用手指划过 UITableViewCell 来进行删除的动作。接下来,置入以下方法,tableView: commitEditingStyle: forRowAtIndexPath:,此方法为根据 UITableView 回传的编辑模式,进行对应的处理方法。

 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {

 //先行删除阵列中的物件
 [self.items removeObjectAtIndex:indexPath.row];

 //删除 UITableView 中的物件,并设定动画模式
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } 
 }
 

注意:NSMutableArray 和 NSArray 的区别

 

来源:http://furnacedigital.blogspot.com/2011/08/uitableview_22.html

 

其他方法:

 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
//这个方法返回指定的 row 的高度。
  
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
//这个方法返回指定的 section的header view 的高度。
  
 - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
//这个方法返回指定的 section的footer view 的高度。
  
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
//返回指定的row 的cell。这个地方是比较关键的地方,一般在这个地方来定制各种个性化的 cell元素。这里只是使用最简单最基本的cell 类型。其中有一个主标题 cell.textLabel 还有一个副标题cell.detailTextLabel,  还有一个 image在最前头 叫cell.imageView.  还可以设置右边的图标,通过cell.accessoryType 可以设置是饱满的向右的蓝色箭头,还是单薄的向右箭头,还是勾勾标记。  
  
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//返回指定的 section 的header的高度
  
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//返回指定的section 的 header  的 title,如果这个section header  有返回view,那么title就不起作用了。
  
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//返回指定的 section header 的view,如果没有,这个函数可以不返回view
  
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//当用户选中某个行的cell的时候,回调用这个。但是首先,必须设置tableview的一个属性为可以select 才行。
  
TableView.allowsSelection=YES;  
cell.selectionStyle=UITableViewCellSelectionStyleBlue; 

//如果不希望响应select,那么就可以用下面的代码设置属性:
TableView.allowsSelection=NO;
 
//下面是响应select 点击函数,根据哪个section,哪个row 自己做出响应就好啦。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	if (indexPath.section == 1) 
	{
		return;
	}
	else if(indexPath.section==0)
	{
		switch (indexPath.row) 
		{
			//聊天
			case 0:
			{
				[self  onTalkToFriendBtn];
			}
				break;
				
			default:
				break;
		}
	}
	else 
	{
		return ;
	}
	
}
 

//如何让cell 能够响应 select,但是选中后的颜色又不发生改变呢,那么就设置 cell.selectionStyle = UITableViewCellSelectionStyleNone;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //cell被选中后的颜色不变
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
  
//如何设置tableview  每行之间的 分割线
self.tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
//如果不需要分割线,那么就设置属性为 UITableViewCellSeparatorStyleNone  即可。

 

//如何设置 tableview cell的背景颜色
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   		//设置背景颜色
		cell.contentView.backgroundColor=[UIColor colorWithRed:0.957 green:0.957 blue:0.957 alpha:1];
}
 
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
//这个函数响应,用户点击cell 右边的 箭头(如果有的话)
 
//如何设置tableview 可以被编辑,首先要进入编辑模式:
[TableView setEditing:YES animated:YES];

  如果要退出编辑模式,肯定就是设置为NO

 

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//返回当前cell  要执行的是哪种编辑,下面的代码是 返回 删除  模式
 
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
 
-(void) tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//通知告诉用户编辑了 哪个cell,对应上面的代码,我们在这个函数里面执行删除cell的操作。
 
-(void) tableView:(UITableView *)aTableView
commitEditingStyle:(UITableViewCellEditingStyle) editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    	[chatArray  removeObjectAtIndex:indexPath.row];
	[chatTableView  reloadData];
}
  
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
//获得 某一行的CELL对象
 

 

 

来源:http://blog.csdn.net/tangaowen/article/details/6438362

 

 

 


    
最新技术文章:
▪Android开发之登录验证实例教程
▪Android开发之注册登录方法示例
▪Android获取手机SIM卡运营商信息的方法
▪Android实现将已发送的短信写入短信数据库的...
▪Android发送短信功能代码
▪Android根据电话号码获得联系人头像实例代码
▪Android中GPS定位的用法实例
▪Android实现退出时关闭所有Activity的方法
▪Android实现文件的分割和组装
▪Android录音应用实例教程
▪Android双击返回键退出程序的实现方法
▪Android实现侦听电池状态显示、电量及充电动...
▪Android获取当前已连接的wifi信号强度的方法
▪Android实现动态显示或隐藏密码输入框的内容
▪根据USER-AGENT判断手机类型并跳转到相应的app...
▪Android Touch事件分发过程详解
▪Android中实现为TextView添加多个可点击的文本
▪Android程序设计之AIDL实例详解
▪Android显式启动与隐式启动Activity的区别介绍
▪Android按钮单击事件的四种常用写法总结
技术文章 iis7站长之家
▪Android实现Back功能代码片段总结
▪Android实用的代码片段 常用代码总结
▪Android实现弹出键盘的方法
▪Android中通过view方式获取当前Activity的屏幕截...
▪Android提高之自定义Menu(TabMenu)实现方法
▪Android提高之多方向抽屉实现方法
▪Android提高之MediaPlayer播放网络音频的实现方法...
▪Android提高之MediaPlayer播放网络视频的实现方法...
▪Android提高之手游转电视游戏的模拟操控
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3