一个Table View一般要设置其dataSource和delegate.
可以通过Control+drag来设置

IOS Table View

IOS Table View


并采用两个协议
@interface SecondViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
UITableViewDelegate协议定义的方法中常用的有:

// Called after the user changes the selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;

// Variable height support
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

UITableViewDataSource协议定义的方法中常用的有:

@required

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

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

注意上面的@required -- 这两方法是必须实现的,否则程序会出错.

如何设置Table View分组显示?
实现下面这个函数:

- (NSString *)tableView:(UITableView *)tableView 
titleForHeaderInSection:(NSInteger)section {
    NSArray *keys = [[[self artists] allKeys] 
                     sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    return [keys objectAtIndex:section];
}

这里的artists定义为NSDictionary *artists;
上面这个函数实现了按artists中的key来分组.

实现如下风格的table view

IOS Table View

1 首先要设置Style 为grouped

IOS Table View
2 实现如下函数

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
设置每个section的标题, 比如上面的UIButton, UIButtonTypeRoundedRect就是Section的标题.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
设置每个Section里面有多少行, 上图中这个值为2

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
总共有多少个Section
上面这些函数要根据你实际要显示的数据来实现.



转载于:https://www.cnblogs.com/uvsjoh/archive/2012/08/15/2640784.html

相关文章: