当app界面大量要使用tableView来布局时,你是否困扰于Class数量太多,需要修改是,疲于寻找对应的Model、View、Controller,现在本文介绍一下解决这个烦恼的一个办法,希望对读者有帮助;以下默认成功加载所创建的页面,代码如下:
类名 - KGDemo.h
#import <UIKit/UIKit.h>
/**
* ----- Model -----
*/
@interface Model : NSObject
@property (nonatomic,strong) NSString *content;
@end
/**
* ----- View -----
*/
@interface View : UITableViewCell
//#import "View.xib"
@property (nonatomic,strong)Model *model;
@property (weak, nonatomic) IBOutlet UIButton *selectBtn;// xib - linked
+(NSString *)cellID;
@end
/**
* ----- Controller -----
*/
@interface KGDemo : UIViewController
@end
类名 - KGDemo.m
#import "KGDemo.h"
/**
* ----- Model -----
*/
@implementation Model
@end
/**
* ----- View -----
*/
@interface View ()
@property (weak, nonatomic) IBOutlet UILabel *selectContent;// xib - linked
@end
@implementation View
+(NSString *)cellID
{
static NSString * const ID = @"ViewID";
return ID;
}
-(void)setModel:(Model *)model{
_selectContent.text = model.content;
_selectBtn.selected = NO;
}
@end
/**
* ----- Controller -----
*/
@interface KGDemo ()<UITableViewDelegate,UITableViewDataSource>
{
NSIndexPath *_selectIndexPath;//选中cell的indexPath
}
@property (weak, nonatomic) IBOutlet UITableView *KGDemoTv;// xib - linked - 在xib中设置delegate、dataSource-
@end
@implementation KGDemo
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"tableView单选功能";
//注册cell
[_KGDemoTv registerNib:[UINib nibWithNibName:NSStringFromClass([View class] ) bundle:nil] forCellReuseIdentifier:[View cellID]];
}
#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_selectIndexPath = indexPath;
[_KGDemoTv reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
View *cell = [tableView dequeueReusableCellWithIdentifier:[View cellID] forIndexPath:indexPath];//注意!!View.xib需要经过特殊处理,否则会在此处崩溃!
Model *model = [Model new];
model.content = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
cell.model = model;
if (_selectIndexPath.row == indexPath.row) {
cell.selectBtn.selected = YES;
}
return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 60;
}
@end
KGDemo.xib中就拉了一个tableView,并设置了一下delegate和dataSource;
然后,最容易出错的地方来了,创建一个空的xib,并命名"View";对View.xib相关操作步骤,如图:
纠正一下:步骤“2选中此处”有误,应选中View(TableViewCell图标),只是设置Class时这样做,其他照原样!
运行截图: