UITableViewCell總結

// 注意:
1. 通過xib來創建UITableViewCell需要在xib的identity上寫上重用標識

 2. 通過storyboard來創建UITableViewCell需要在storyboard的identity上寫上重用標識

 3.  有時候每一行的cell用的不一定是同一種UITableVIewCell,對象池中也會有不同的UITableViewCell等待重用,那么在重用的時候可能得到的是錯誤的UITableViewCell}
     解決方法:可以通過重用屬性reuseIdentifier來對應不同的UITableViewCell

 4. 往cell添加子控件的時候,把子控件添加到contentView上面

 5. 不應該在initWithStyle中設置子控件的Frame,因為父控件的Frame還沒有確定,子控件設置Frame不太好,我們應該在layoutSubviews中設置Frame
 layoutSubviews (一定要調用父類) :
    當一個控件的frame發生改變的時候調用,Frame前后要不一致
    將一個控件添加到當前控件的時候調用

一、UITableViewCell重用的封裝

+ (instancetype)HeroCell:(UITableView *)tableView;{
    HeroTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (!cell) {
        cell = [[HeroTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ID"];
    }
    return cell;
}

二、UITableViewCell的封裝 - 系統自定義

#import <UIKit/UIKit.h>
@class Hero;
@interface HeroTableViewCell : UITableViewCell
+ (instancetype)HeroCell;
@property (nonatomic, strong) Hero *hero;
@end
#import "HeroTableViewCell.h"
#import "Hero.h"
@implementation HeroTableViewCell
+ (instancetype)HeroCell{
    HeroTableViewCell *cell = [[HeroTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
    return cell;
}

- (void)setHero:(Hero *)hero{
    _hero = hero;
    self.imageView.image = [UIImage imageNamed:hero.icon];
    self.textLabel.text = hero.name;
    self.detailTextLabel.text = hero.intro;
}
@end

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Hero *hero = self.heros[indexPath.row];
    HeroTableViewCell *cell = [HeroTableViewCell HeroCell];
    cell.hero = hero;
    return cell;
}

三、UITableViewCell的封裝 - 動態單元格
1.動態單元格得使用UITableViewController

2.UITableViewController的動態單元格cell要寫自定義的UITableViewCell,從而通過UITableViewCell實現自定義

3.UITableViewCell -> AppViewCell的代碼實現

#import <UIKit/UIKit.h>
@class App;
@class AppViewCell;
/// 代理
@protocol AppViewCellDelegate <NSObject>
@optional
- (void)downloadBtnDidClick:(AppViewCell *)appViewCell;
@end

@interface AppViewCell : UITableViewCell
+ (instancetype) appViewCell:(UITableView *)tableView;
@property (nonatomic, strong) App *app;
/// 代理屬性
@property (nonatomic, assign) id<AppViewCellDelegate> delegate;
@end
#import "AppViewCell.h"
#import "App.h"

@interface AppViewCell ()
/// 屬性連線
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameView;
@property (weak, nonatomic) IBOutlet UILabel *detailView;
@property (weak, nonatomic) IBOutlet UIButton *downloadBtn;
@end

@implementation AppViewCell
- (IBAction)downloadBtnDidClick {
    /// 禁用下載按鈕
    self.downloadBtn.enabled = NO;
    /// 設置已下載
    self.app.isDownloaded = YES;
    /// 判斷代理是否實現了代理方法
    if ([self.delegate respondsToSelector:@selector(downloadBtnDidClick:)]) {
        [self.delegate downloadBtnDidClick:self];
    }
}

+ (instancetype)appViewCell:(UITableView *)tableView{
    //dequeueReusableCellWithIdentifier會從緩存中創建Cell,但是如果緩存中沒有可重用的cell,則查詢系統的cell原型,通過原型創建cell,.沒有原型則報錯:
    AppViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"app"];
    return cell;
}

- (void)setApp:(App *)app{
    _app = app;
    self.iconView.image = [UIImage imageNamed:app.icon];
    self.nameView.text = app.name;
    self.detailView.text=[NSString stringWithFormat:@"大小:%@M,下載數量:%@",app.size,app.download];
    self.downloadBtn.enabled = !app.isDownloaded;
}
@end

四、UITableViewCell的封裝 - xib
1.xib名和UITableViewCell名一般相同
2.xib中的控件要進行屬性連線
3.代碼實現

#import <UIKit/UIKit.h>
@class CZTg;

@interface CZTgCell : UITableViewCell
//返回當前自定義的cell
+ (instancetype) tgCell:(UITableView *)tableView;
//為當前自定義cell賦值
@property (nonatomic,strong) CZTg *tg;

@end
#import "CZTgCell.h"
#import "CZTg.h"

@interface CZTgCell()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *titleView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *buyCountView;
@end
@implementation CZTgCell

//創建自定義cell
+ (instancetype)tgCell:(UITableView *)tableView
{
    //1.定義重用標識
    NSString *ID=@"tg";
    //2.從緩存中創建cell
    CZTgCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    //3.判斷是否成功創建出cell,如果沒有就自己從Xib中創建
    if (cell==nil) {
        NSLog(@"aaaaaaa");
        cell=[[[NSBundle mainBundle] loadNibNamed:@"CZTgCell" owner:self options:nil] lastObject];
    }
    return  cell;
}

- (void)setTg:(CZTg *)tg
{
    _tg=tg;
    self.iconView.image=[UIImage imageNamed:tg.icon];
    self.titleView.text=tg.title;
    self.priceView.text=[NSString stringWithFormat:@"¥%@",tg.price];
    self.buyCountView.text=[NSString stringWithFormat:@"%@人已購買",tg.buyCount];
}
@end

五、UITableViewCell的封裝 - 純代碼
1.思路:
1.1重寫UITableViewCell的initWithStyle方法(記得先super父類方法),在方法中新建控件并添加到cell中,再設置控件的屬性值
1.2在-(void)setMessageFrame方法中設置數據
1.3在-(void)layoutSubviews中設置Frame (layoutSubviews是在子控件添加到父類的時候會調用)
2.控件的Frame已經在模型中實現了,所以cell就不需要再設置Frame
3.代碼的實現:

#import <UIKit/UIKit.h>
@class CZMessageCellFrame;

@interface CZMessageCell : UITableViewCell
+ (instancetype) messageCell:(UITableView *)tableView;

@property (nonatomic,strong) CZMessageCellFrame *messageFrame;
@end
#import "CZMessageCell.h"
#import "CZMessage.h"
#import "CZMessageCellFrame.h"

@interface CZMessageCell ()
@property (nonatomic,weak) UILabel *timeView;
@property (nonatomic,weak) UIImageView *iconView;
@property (nonatomic,weak) UIButton *textView;
@end

@implementation CZMessageCell

+ (instancetype) messageCell:(UITableView *)tableView
{
    NSString *ID=@"QQ";
    CZMessageCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        //這個方法是父類的方法,也就意味著它只能創建出父類中默認的系統自帶的cell.而不能滿足我們的需要,所以我們就需要做重寫,在調用方法的時候調用我們子類自己重寫過后的方法。
        cell=[[CZMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    return  cell;
}
//根據多態,系統會根據類型調用子類重寫過后的方法
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    //1.先初始化父類成員
    self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //1.添加timeView
        UILabel *timeView=[[UILabel alloc] init];
        self.timeView=timeView;
        //設置居中
        timeView.textAlignment=NSTextAlignmentCenter;
        timeView.font=[UIFont systemFontOfSize:13];
        timeView.textColor=[UIColor lightGrayColor];
        [self addSubview:timeView];
        //2.添加iconView
        UIImageView *iconView=[[UIImageView alloc] init];
        self.iconView=iconView;
        [self addSubview:iconView];
        //3.添加textView
        UIButton *textView=[[UIButton alloc] init];
        self.textView=textView;
        //設置按鈕的文本色
        [textView setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //設置按鈕的字體大小
        textView.titleLabel.font=[UIFont systemFontOfSize:14];
        //設置自動換行
        textView.titleLabel.numberOfLines=0;
        //為按鈕添加內容的內間距
        textView.contentEdgeInsets=UIEdgeInsetsMake(0, 20, 0, 20);
        //為按鈕添加背景色
        //textView.backgroundColor=[UIColor redColor];
        [self addSubview:textView];
    }
    return self;
}

- (void)setMessageFrame:(CZMessageCellFrame *)messageFrame
{
    _messageFrame=messageFrame;
    //設置數據
    [self setDatas];
}
//設置數據
- (void) setDatas
{
    CZMessage *msg=self.messageFrame.message;

    self.timeView.text=msg.time;

    if (msg.type==MessageTypeMe) {
        self.iconView.image=[UIImage imageNamed:@"me"];
        //根據消息類型設置消息文本的背景圖片
        [self.textView setBackgroundImage:[self resizeImageWithName:@"chat_send_nor"] forState:UIControlStateNormal];
        [self.textView setBackgroundImage:[self resizeImageWithName:@"chat_send_press_pic"] forState:UIControlStateHighlighted];
    }
    else
    {
        self.iconView.image=[UIImage imageNamed:@"other"];
        [self.textView setBackgroundImage:[self resizeImageWithName:@"chat_recive_nor"] forState:UIControlStateNormal];
        [self.textView setBackgroundImage:[self resizeImageWithName:@"chat_recive_press_pic"] forState:UIControlStateHighlighted];
    }
    [self.textView setTitle:msg.text forState:UIControlStateNormal];

}

//返回拉伸之后的圖片
- (UIImage *) resizeImageWithName:(NSString *)name
{
    return [[UIImage imageNamed:name] resizableImageWithCapInsets:UIEdgeInsetsMake(30, 20, 18, 30) resizingMode:UIImageResizingModeStretch];
}

//當將當前控件添加到父容器的時候,自動調用這個方法,設置它的子控件的Frame
//如現在這個情況:當創建好cell,添加到tableView中的時候,會調用這個方法設置cell 的三個子控件的frame
- (void) layoutSubviews
{
    //判斷是否需要顯示時間
    self.timeView.hidden=! self.messageFrame.showTime;
    self.timeView.frame=self.messageFrame.timeViewF;
    self.iconView.frame=self.messageFrame.iconViewF;
    self.textView.frame=self.messageFrame.textViewF;
}
@end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,250評論 4 61
  • UITableViewCell 父類是UIView UITableView的每一行都是一個UITableViewC...
    翻這個墻閱讀 6,676評論 0 1
  • 1.屬性readwrite,readonly,assign,retain,copy,nonatomic 各是什么作...
    曾令偉閱讀 1,080評論 0 10
  • 一大早朋友打電話送來幾張票:“今晚七點,來看我們縣的春晚!” 盡管不是演員,到現場的那一刻也是無比激動的:絢麗的舞...
    時光呵閱讀 153評論 0 0
  • 半夜 生物鐘把我鬧醒 床頭迷籠的光 黑夜里充盈的瞳眸 母親這疲累卑小的身份 時常驕傲里填滿喪氣 時常心安里澆灌惶恐...
    半壁殘月閱讀 334評論 2 4