當(dāng)app界面大量要使用tableView來布局時任斋,你是否困擾于Class數(shù)量太多荤傲,需要修改是,疲于尋找對應(yīng)的Model烘绽、View淋昭、Controller,現(xiàn)在本文介紹一下解決這個煩惱的一個辦法诀姚,希望對讀者有幫助;以下默認成功加載所創(chuàng)建的頁面玷禽,代碼如下:
類名 - 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中設(shè)置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需要經(jīng)過特殊處理糯笙,否則會在此處崩潰!
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撩银,并設(shè)置了一下delegate和dataSource给涕;
然后,最容易出錯的地方來了,創(chuàng)建一個空的xib够庙,并命名"View"恭应;對View.xib相關(guān)操作步驟,如圖:
糾正一下:步驟“2選中此處”有誤耘眨,應(yīng)選中View(TableViewCell圖標(biāo))昼榛,只是設(shè)置Class時這樣做,其他照原樣剔难!
運行截圖: