我需要一段iOS Tableview代码
时间: 2023-09-15 12:21:30 浏览: 187
好的,以下是一个简单的iOS Tableview代码示例:
首先,在你的ViewController.h文件中添加UITableViewDelegate和UITableViewDataSource协议:
```
@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
```
然后,在你的ViewController.m文件中,初始化一个UITableView,并实现UITableViewDataSource和UITableViewDelegate协议的方法:
```
- (void)viewDidLoad {
[super viewDidLoad];
UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10; // 返回10行
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"Row %ld", (long)indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(@"Selected row %ld", (long)indexPath.row);
}
```
这个示例会在你的ViewController上创建一个UITableView,其中包含10行简单的文本。当你点击任何一行时,它会在控制台上打印所选行的索引。
希望这可以帮助你开始实现你自己的表视图!
阅读全文
相关推荐


















