iOS UITableView的简单使用

使用UITableView进行简单开发

1.类继承<UITableViewDelegate,UITableViewDataSource> 并添加一个UITableView属性,和一个数组,这个数组是表格上显示的数据

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSArray *array;

@end

2.在- (void)viewDidLoad 初始化tableView,并添加代理

CGRectMake(0, 0, 300, 400) 的前两个数字是 坐标, 后两个数字是这个tableView的宽高


- (void)viewDidLoad {
    
    [super viewDidLoad];
    //初始化这个数组
    self.array = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
    //添加代理
    [self.tableView setDelegate:self];
    
    [self.tableView setDataSource:self];
    //把表格添加到一个控件中
    [self.view addSubview:self.tableView];
	//刷新表格
    [self.tableView reloadData];
    
}


3.添加代理方法
//表格行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}


//表格行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}


//初始化cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
    //indexPath.row表示这是第几行,从0开始
    NSString *showStr = self.array[indexPath.row];
    [label setText:showStr];
    [label setTextAlignment:NSTextAlignmentCenter];
    [cell.contentView addSubview:label];
    return cell;
}


//行点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *showStr = self.array[indexPath.row];
    NSLog(@"%@",showStr);
}



附加
//在初始化cell时加上这一句,可以让点击特效消失.不影响功能
cell.selectionStyle = UITableViewCellSelectionStyleNone;


//在初始化tableView时时加上这一句,可以让行不显示分割线
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;


//这一句在初始化cell时设置下划线,下面的四个参数都是数字
cell.separatorInset = UIEdgeInsetsMake(cell.separatorInset.top, cell.separatorInset.left, cell.separatorInset.bottom, cell.separatorInset.right);


表格嵌套使用>>>ios UITableView行内嵌横向UICollectionView
UICollectionView的简单使用>>>UICollectionView的简单使用

发布了31 篇原创文章 · 获赞 30 · 访问量 7391

猜你喜欢

转载自blog.csdn.net/qq_41586150/article/details/104083755