简单的tableView哦,和列表一样,只有lable和image,很简单哦~~ 233~~~
上代码啦~~~
.h的代码
#import <UIKit/UIKit.h>
//加UITableViewDataSource,UITableViewDelegate委托代理,具体代码在.m中实现
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
//字符串数组
@property (nonatomic,strong) NSArray *listData;
//图片数组
@property (nonatomic , strong) NSArray *listImage;
//tableView声明
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@end
.m文件的代码
@implementation ViewController
//返回数据数组的个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_listData count];
}
//设置tableview的cell,就是没一行的数据
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//这里要注意cell的复用
//相当于cell的tag,方便后面复用吧~~我是这么理解的
static NSString *cellDentifier = @"cell";
//声明cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellDentifier];
if(cell == nil){
//UITableViewCellStyleDefault:cell的样式,reuseIdentifier:cell的复用
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellDentifier];
}
//设置cell的lable,indexPath.row获取cell的position
cell.textLabel.text = _listData[indexPath.row];
//设置cell的image
cell.imageView.image = [UIImage imageNamed:_listImage[indexPath.row]];
return cell;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//声明字符串数组
NSArray *datas = [[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22", nil];
//声明图片数组
NSArray *images = [[NSArray alloc]initWithObjects:@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png",@"tab_nor.png", nil];
//把当前数组赋值给.h中声明的数组
self.listData = datas;
self.listImage = images;
}
//这个事件是点击某一行数据时执行的操作
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//获取到当前点击这一行的数据用initWithFormat拼接成字符串
NSString *message = [[NSString alloc]initWithFormat:@"你选择了%@", _listData[indexPath.row]];
//这个是显示一个alert
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选中" message: message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
//点击后会有按下效果,这个是执行操作后消除这一行的效果
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
nib文件注意dataSource和delegate的拖拽,要拖到File’s Owner上哦~ 233~~~
还要注意tableView和.h文件的关联呢~~~
问题:
这次我遇到什么问题呢,布局的问题,没有加约束之前,列表没有靠近底部,留有一片空白,加了到顶部、左、右、底部都为0的约束之后就充满了屏幕~~
大家会加约束吗?点完约束记得点下边的Add constraints哦~~
我经常忘~233~