自定义UITableViewCell
很多时候,我们是不能直接使用系统自带的UITableViewCell,因为自带的比较简单只有一个UIImageView和两个UILabel,假设需要多个UIImageView或者两个以上UILabel,那就需要自定义了。本文就实现如何自定义UITableViewCell。
假设我们现在需要实现一个新闻列表。
1.自定义NewTableViewCell.h如下:
//
// NewTableViewCell.h
// iosstudy2024
//
// Created by figo on 2024/12/26.
//
#import <UIKit/UIKit.h>
#import "New.h"
NS_ASSUME_NONNULL_BEGIN
@interface NewTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *lblTitle;
@property (weak, nonatomic) IBOutlet UILabel *lblTime;
@property (weak, nonatomic) IBOutlet UILabel *lblContent;
@property (weak, nonatomic) IBOutlet UIImageView *imgIcon;
-(void)configCell:(New *)new;
@end
NS_ASSUME_NONNULL_END
NewTableViewCell.m如下
//
// NewTableViewCell.m
// iosstudy2024
//
// Created by figo on 2024/12/26.
//
#import "NewTableViewCell.h"
@implementation NewTableViewCell
-(void)configCell:(New *)new{
self.imageView.image=[UIImage imageNamed:new.picName];
self.lblTitle.text=new.title;
self.lblTitle.textColor=[UIColor redColor];
self.lblTitle.font=[UIFont systemFontOfSize:12];
self.lblTime.text=new.time;
self.lblContent.text=new.content;
float width=[UIScreen mainScreen].bounds.size.width;
float height=[UIScreen mainScreen].bounds.size.height;
[self setFrame:(CGRectMake(0, 0, width, 100))];
}
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
2.新闻列表控制器NewsViewController
xib页面很简单就放了一个UITableView
NewsViewController.h代码如下:
//
// NewsViewController.h
// iosstudy2024
//
// Created by figo on 2024/12/26.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface NewsViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
NewsViewController.m 如下:
//
// NewsViewController.m
// iosstudy2024
//
// Created by figo on 2024/12/26.
//
#import "NewsViewController.h"
#import "New.h"
#import "NewTableViewCell.h"
@interface NewsViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *newsUITableView;
@property(strong,nonatomic) NSMutableArray *allNews;
@end
@implementation NewsViewController
//-(NSMutableArray *)news{
// if(_news==nil){
// _news=[[New alloc]getModels];
// }
// return _news;
//}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//通过实现UITableViewDataSource,UITableViewDelegate协议,将数据源和代理设置为自身
self.newsUITableView.dataSource=self;
self.newsUITableView.delegate=self;
self.newsUITableView.rowHeight=100;
//2.获取屏幕宽度
float width=[UIScreen mainScreen].bounds.size.width;
float height=[UIScreen mainScreen].bounds.size.height;
NSLog(@"@width,%height",width,height);
[self.newsUITableView setFrame:CGRectMake(0, 0, width, height)];
//table脚设置后就不会出现空白行
self.newsUITableView.tableFooterView=[[UIView alloc]init];
//设置models
self.allNews=[[[New alloc]init]getModels];
printf("allNews count=%d \n",self.allNews.count);
//关联自定义NewTableViewCell到当前页面的tableView
UINib * nib=[UINib nibWithNibName:@"NewTableViewCell" bundle:nil];
[self.newsUITableView registerNib:nib forCellReuseIdentifier:@"test"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//printf("news count=%d",self.news.count);
return self.allNews.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NewTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"test"];
float width=[UIScreen mainScreen].bounds.size.width;
cell.frame=CGRectMake(0, 0, width, 100);
//设置图片,标题,时间,内容
[cell configCell:[self.allNews objectAtIndex:indexPath.row]];
//设置图片大小,直接在NewTableViewCell里面写,发现不生效,需要在这里写
CGSize itemSize = CGSizeMake(30, 30);
UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[cell.imageView.image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
//设置图片自适应比例
//[cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
UIGraphicsEndImageContext();
return cell;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
3.新闻Model如下:
New.h
//
// New.h
// iosstudy2024
//
// Created by figo on 2025/1/2.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface New : NSObject
//新闻图片
@property(nonatomic,copy) NSString *picName;
//标题
@property(nonatomic,copy) NSString *title;
//时间
@property(nonatomic,copy) NSString *time;
//内容
@property(nonatomic,copy) NSString *content;
//获取models方法
-(NSMutableArray *)getModels;
@end
NS_ASSUME_NONNULL_END
New.m
//
// New.m
// iosstudy2024
//
// Created by figo on 2025/1/2.
//
#import "New.h"
@interface New()
@property(strong,nonatomic) NSArray *pics;
@property(strong,nonatomic) NSArray *titles;
@property(strong,nonatomic) NSArray *times;
@property(strong,nonatomic) NSArray *contents;
@property(strong,nonatomic) NSMutableArray *news;
@end
@implementation New
-(NSArray *)pics{
if(_pics==nil){
_pics=@[@"star",@"star",@"star",@"star",@"star",@"star"];
}
return _pics;
}
-(NSArray *)titles{
if(_titles==nil){
_titles=@[@"元旦放假通知",@"银行贷款利率下降",@"解放台湾进行时",@"中国与周边国家关系改善",@"美加关税促进中欧,中亚,中非,中澳合作",@"经济向好,薪资普涨"];
}
return _titles;
}
-(NSArray *)times{
if(_times==nil){
_times=@[@"2024-12-31",@"2025-01-01",@"2025-01-01",@"2025-01-01",@"2025-01-02",@"2025-01-02"];
}
return _times;
}
-(NSArray *)contents{
if(_contents==nil){
_contents=@[@"2025年1月1日全国放假一天",@"银行贷款利率普遍低于3%",@"民进党当局执迷不悟,民众投票选择与大陆和平统一",@"中日,中印,中菲关系改善,逐步走向互惠!",@"美与全世界为敌,美国优先的结果是孤立了自己,促进了中国与其他国家的贸易量上升",@"随着经济好转,企业收入增加,员工薪资普涨。"];
}
return _contents;
}
//懒加载
-(NSMutableArray *)news{
NSInteger count=self.titles.count;
if(_news==nil){
_news=[NSMutableArray array];
for(int m=0;m<count;m++){
New *new=[[New alloc]init];
new.title=self.titles[m];
new.picName=self.pics[m];
new.time=self.times[m];
new.content=self.contents[m];
[_news addObject:new];
}
}
return _news;
}
-(NSMutableArray *)getModels{
return self.news;
}
@end
4.SceneDelegate.m将控制器指向NewsViewController
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
//默认是使用ViewController,这里改成WidgetViewController为根视图
// TableViewTestViewController * wvc = [[TableViewTestViewController alloc]init];
//[self.window setRootViewController:wvc];
NewsViewController * nvc = [[NewsViewController alloc]init];
self.window.rootViewController=nvc;
}
5.运行效果: