自定义一个tableViewCell的方法

本文介绍如何在iOS应用中使用TableView并自定义单元格显示内容。通过注册自定义的TableViewCell类,实现了每个单元格内LABEL的展示,并对其样式进行了配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

viewcontroller.m里的代码

#import "ViewController.h"
#import "TableViewCell.h"

@interface ViewController () <UITableViewDataSource,UITableViewDelegate>
{
    UITableView *MytableView;
}

@end

@implementation ViewController
            
- (void)viewDidLoad {
    [super viewDidLoad];
    
    MytableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    MytableView.delegate = self;
    MytableView.dataSource = self;
    [self.view addSubview:MytableView];

    [MytableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
  


}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableViewCell *cell = [MytableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    return cell;
}


自定义的tableviewcell.h

#import <UIKit/UIKit.h>

@interface TableViewCell : UITableViewCell

@property (nonatomic,strong) UILabel *label ;
@end

tableviewcell.m

#import "TableViewCell.h"

@implementation TableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        _label = [[UILabel alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
        _label.text = @"1234 ";
        _label.textColor = [UIColor redColor];
        [self.contentView addSubview:_label];
       
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.label.frame = CGRectMake(200, 10, 50, 20);
    self.label.textColor = [UIColor blueColor];
    self.label.text = @"123";
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值