博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

UITableView用法总结

Posted on 2011-07-18 20:33  星尘的天空  阅读(1151)  评论(0编辑  收藏  举报

这一节主要讲解对UITableView的理解

IPhone的应用程序是离不开UITableView应用程序的,因此理解Table控件特别的重要。

下面主要是对UITableView显示数据的两种方式进行讲解。

Part1:

显示数据的内容主要是UITableView控件,但是我们需要定义一个类为他加载数据,以及定义和用户交互交互的回调函数,这两个方面是通过委托的形式实现的。根据MVC的设计形式,Apple将UITableView放置到一个UITableViewController类当中,使用UITableViewController类实例来控制UITableView的更个方面的属性。我们需要创建这么一个controller类型的类,这种类可以通过继承成为UITableView的父类,也可以不继承这个类,仅仅实现数据源委托以及操作委托即可。

1:创建基于UITableViewController的子类。

@interface RootViewController : UITableViewController {

NSArray *dataArray ;

}

@property(nonatomic,retain) NSArray *dataArray ;

因为UITableViewController类已经包含了委托<UITableViewDelegate, UITableViewDataSource>,因此我们在这里就不需要手动添加这些委托。我们可以通过查看源代码来查看我们的假设:

UIKIT_EXTERN_CLASS @interface UITableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

{

  @private

    UITableViewStyle _tableViewStyle;

    id               _keyboardSupport;

    struct {

        int clearsSelectionOnViewWillAppear:1;

    } _tableViewControllerFlags;

}

通过上面的代码我们可以看到UITableViewController已经继承了<UITableViewDelegate, UITableViewDataSource>这两个委托。

这样以来,在实现文件里面我们仅仅需要实现这两个委托里面的必须实现的函数就可以了。

但是,到这里我们还是不可以的,我们还没有完完成任务。 我们创建的这个类还是需要一个能够装载这个类的实例的容器来着,这就好像,我们去买一瓶矿泉水,水是必须装在一个瓶子(容器)里面才可以拿着喝得。 我们创建的这个类的实例,就好比水,我们还需要创建一个瓶子(容器)来装这些水 。这个容器可以是一个UIView实例,或者是一个UINavigationController实例,或者是一个Nib文件都可以,这些准备完毕后就可以看到效果了。

2:现在我们来看第二种情况,创建普通控制类的实例。  

如果我们创建普通控制类的实例,比如如下面所示:

@interface RootViewController:UITableViewController

<UITableViewDelegate,UITableViewDataSource>

{

NSArray *dataArray;

}

@property(nonatomic,retain) NSArray *dataArray ;

这种情况下,我们需要手动的添加来继承委托,实现数据源的继承以及数据操作的继承。

然后剩下的情况就和其他上面的一样来,实现委托中定义的必须要实现的类,加载数据,加载数据到容器中,然后显示数据。



Part2:创建一个简单的表格

参考代码:

//.h

@interface ViewBaseAppViewController : UIViewController 

<UITableViewDelegate,UITableViewDataSource>

{

IBOutlet UITableView *m_tableView;

}

//.m

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

    // Return the number of rows in the section.

return 10;

}

- (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 =@"xingchen";

    

    return cell;

}