ios tableView实现单选

作者: oc123 | 来源:发表于2017-05-11 17:19 被阅读29次

为了使代码结构更加合理、精简,本人将M层和V层进行了合并,本文主要介绍tableView的单选功能实现和MV合并,代码如下:
类名 - View.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 -
+(NSString *)cellID;
@end

类名 - View.m

#import "View.h"
/**
 *  ----- Model -----
 */
@implementation Model
@end

/**
 *  ----- View -----
 */
@interface View ()
@property (weak, nonatomic) IBOutlet UILabel *selectContent;// - xib -
@end

@implementation View
+(NSString *)cellID
{
    static NSString * const ID = @"ViewID";
    return ID;
}
-(void)setModel:(Model *)model{
    _selectContent.text = model.content;
    _selectBtn.selected = NO;
}
@end

类名 - KGDemo.h

#import <UIKit/UIKit.h>

/**
 *  ----- Controller -----
 */
@interface KGDemo : UIViewController

@end

类名 - KGDemo.m

#import "KGDemo.h"
#import "View.h"

/**
 *  ----- Controller -----
 */
@interface KGDemo ()<UITableViewDelegate,UITableViewDataSource>
{
    NSIndexPath *_selectIndexPath;//选中cell的indexPath
}
@property (weak, nonatomic) IBOutlet UITableView *KGDemoTv;// - 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]];
    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

运行截图:


运行效果图.png

相关文章

网友评论

    本文标题:ios tableView实现单选

    本文链接:https://www.haomeiwen.com/subject/ejbotxtx.html