UITableView(一)

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

    @property (nonatomic, retain) NSArray *_dataList;
    @property (nonatomic, retain) UITableView *_myTableView;

@end
//
//  ViewController.m
//  ios13
//
//  Created by fredric on 16/4/14.
//  Copyright © 2016年 fredric. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *list = [NSArray arrayWithObjects:@"条目1",@"条目2", nil];
    self._dataList = list;
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    
    self._myTableView = tableView;
    
    [self.view addSubview:self._myTableView];
    
}

#pragma mark - Table view data source
/*-
 *  创建某个section及某个row中UITableViewCell的定义
 * NSIndexPath 包含sectoin、row两个方法获取对应的section和row
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //通过Identifier在tableView的缓冲池中寻找cell对象
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    
    if(cell == nil){
        //若缓冲池中没有则创建这个对象
        // UITableViewCell 包含四种显示方式
        // UITableViewCellStyleDefault 为默认的左对齐格式
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    cell.textLabel.text = [self._dataList objectAtIndex:[indexPath row]];
    cell.detailTextLabel.text = @"详细信息";
    
    return cell;
}

//一共有多少个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//分区中有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self._dataList count];
}

#pragma mark - Table view delegate
//选择UITableView的某一行
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIAlertView *showSelection;
    showSelection = [[UIAlertView alloc]
                     initWithTitle: @"已经选择了"
                     message: [NSString stringWithFormat: @"%d", [indexPath row]]
                     delegate: nil
                     cancelButtonTitle: @"Ok"
                     otherButtonTitles: nil];
    [showSelection show];
}

@end
原文地址:https://www.cnblogs.com/Fredric-2013/p/5389976.html