ios開發UI篇—使用純代碼自定義UItableviewcell實現一個簡單的微博界面佈局

来源:http://www.cnblogs.com/qianLL/archive/2016/04/01/5346592.html
-Advertisement-
Play Games

本文轉自 :http://www.cnblogs.com/wendingding/p/3761730.html ios開發UI篇—使用純代碼自定義UItableviewcell實現一個簡單的微博界面佈局 一、實現效果 二、使用純代碼自定義一個tableview的步驟 1.新建一個繼承自UITable ...


 

本文轉自 :http://www.cnblogs.com/wendingding/p/3761730.html

 

ios開發UI篇—使用純代碼自定義UItableviewcell實現一個簡單的微博界面佈局

一、實現效果

 

二、使用純代碼自定義一個tableview的步驟

1.新建一個繼承自UITableViewCell的類

2.重寫initWithStyle:reuseIdentifier:方法

添加所有需要顯示的子控制項(不需要設置子控制項的數據和frame,  子控制項要添加到contentView中)

進行子控制項一次性的屬性設置(有些屬性只需要設置一次, 比如字體\固定的圖片)

3.提供2個模型

數據模型: 存放文字數據\圖片數據

frame模型: 存放數據模型\所有子控制項的frame\cell的高度

4.cell擁有一個frame模型(不要直接擁有數據模型)

5.重寫frame模型屬性的setter方法: 在這個方法中設置子控制項的顯示數據和frame 

6.frame模型數據的初始化已經採取懶載入的方式(每一個cell對應的frame模型數據只載入一次)

三、文件結構和實現代碼

1.文件結構

 

2.實現代碼:

NJWeibo.h文件

複製代碼
 1 #import <Foundation/Foundation.h>
 2 
 3 @interface NJWeibo : NSObject
 4 @property (nonatomic, copy) NSString *text; // 內容
 5 @property (nonatomic, copy) NSString *icon; // 頭像
 6 @property (nonatomic, copy) NSString *name; // 昵稱
 7 @property (nonatomic, copy) NSString *picture; // 配圖
 8 @property (nonatomic, assign) BOOL vip;
 9 
10 - (id)initWithDict:(NSDictionary *)dict;
11 + (id)weiboWithDict:(NSDictionary *)dict;
12 @end
複製代碼

NJWeibo.m文件

複製代碼
 1 #import "NJWeibo.h"
 2 
 3 @implementation NJWeibo
 4 
 5 - (id)initWithDict:(NSDictionary *)dict
 6 {
 7     if (self = [super init]) {
 8         [self setValuesForKeysWithDictionary:dict];
 9     }
10     return self;
11 }
12 
13 + (id)weiboWithDict:(NSDictionary *)dict
14 {
15     return [[self alloc] initWithDict:dict];
16 }
17 
18 @end
複製代碼

NJWeiboCell.h文件

複製代碼
 1 #import <UIKit/UIKit.h>
 2 @class NJWeiboFrame;
 3 
 4 @interface NJWeiboCell : UITableViewCell
 5 /**
 6  *  接收外界傳入的模型
 7  */
 8 //@property (nonatomic, strong) NJWeibo *weibo;
 9 
10 @property (nonatomic, strong) NJWeiboFrame *weiboFrame;
11 
12 + (instancetype)cellWithTableView:(UITableView *)tableView;
13 @end
複製代碼

NJWeiboCell.m文件

複製代碼
  1 #import "NJWeiboCell.h"
  2 #import "NJWeibo.h"
  3 #import "NJWeiboFrame.h"
  4 
  5 #define NJNameFont [UIFont systemFontOfSize:15]
  6 #define NJTextFont [UIFont systemFontOfSize:16]
  7 
  8 @interface NJWeiboCell ()
  9 /**
 10  *  頭像
 11  */
 12 @property (nonatomic, weak) UIImageView *iconView;
 13 /**
 14  *  vip
 15  */
 16 @property (nonatomic, weak) UIImageView *vipView;
 17 /**
 18  *  配圖
 19  */
 20 @property (nonatomic, weak) UIImageView *pictureView;
 21 /**
 22  *  昵稱
 23  */
 24 @property (nonatomic, weak) UILabel *nameLabel;
 25 /**
 26  *  正文
 27  */
 28 @property (nonatomic, weak) UILabel *introLabel;
 29 @end
 30 
 31 @implementation NJWeiboCell
 32 
 33 + (instancetype)cellWithTableView:(UITableView *)tableView
 34 {
 35     // NSLog(@"cellForRowAtIndexPath");
 36     static NSString *identifier = @"status";
 37     // 1.緩存中取
 38     NJWeiboCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
 39     // 2.創建
 40     if (cell == nil) {
 41         cell = [[NJWeiboCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
 42     }
 43     return cell;
 44 }
 45 
 46 
 47 /**
 48  *  構造方法(在初始化對象的時候會調用)
 49  *  一般在這個方法中添加需要顯示的子控制項
 50  */
 51 - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
 52 {
 53     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
 54     if (self) {
 55         // 讓自定義Cell和系統的cell一樣, 一創建出來就擁有一些子控制項提供給我們使用
 56         // 1.創建頭像
 57         UIImageView *iconView = [[UIImageView alloc] init];
 58         [self.contentView addSubview:iconView];
 59         self.iconView = iconView;
 60         
 61         // 2.創建昵稱
 62         UILabel *nameLabel = [[UILabel alloc] init];
 63         nameLabel.font = NJNameFont;
 64         // nameLabel.backgroundColor = [UIColor redColor];
 65         [self.contentView addSubview:nameLabel];
 66         self.nameLabel = nameLabel;
 67         
 68         // 3.創建vip
 69         UIImageView *vipView = [[UIImageView alloc] init];
 70         vipView.image = [UIImage imageNamed:@"vip"];
 71         [self.contentView addSubview:vipView];
 72         self.vipView = vipView;
 73         
 74         // 4.創建正文
 75         UILabel *introLabel = [[UILabel alloc] init];
 76         introLabel.font = NJTextFont;
 77         introLabel.numberOfLines = 0;
 78         // introLabel.backgroundColor = [UIColor greenColor];
 79         [self.contentView addSubview:introLabel];
 80         self.introLabel = introLabel;
 81         
 82         // 5.創建配圖
 83         UIImageView *pictureView = [[UIImageView alloc] init];
 84         [self.contentView addSubview:pictureView];
 85         self.pictureView = pictureView;
 86         
 87     }
 88     return self;
 89 }
 90 
 91 
 92 - (void)setWeiboFrame:(NJWeiboFrame *)weiboFrame
 93 {
 94     _weiboFrame = weiboFrame;
 95     
 96     // 1.給子控制項賦值數據
 97     [self settingData];
 98     // 2.設置frame
 99     [self settingFrame];
100 }
101 
102 
103 /**
104  *  設置子控制項的數據
105  */
106 - (void)settingData
107 {
108     NJWeibo *weibo = self.weiboFrame.weibo;
109     
110     // 設置頭像
111     self.iconView.image = [UIImage imageNamed:weibo.icon];
112     // 設置昵稱
113     self.nameLabel.text = weibo.name;
114     // 設置vip
115     if (weibo.vip) {
116         self.vipView.hidden = NO;
117         self.nameLabel.textColor = [UIColor redColor];
118     }else
119     {
120         self.vipView.hidden = YES;
121         self.nameLabel.textColor = [UIColor blackColor];
122     }
123     // 設置內容
124     self.introLabel.text = weibo.text;
125     
126     // 設置配圖
127     if (weibo.picture) {// 有配圖
128         self.pictureView.image = [UIImage imageNamed:weibo.picture];
129         self.pictureView.hidden = NO;
130     }else
131     {
132         self.pictureView.hidden = YES;
133     }
134 }
135 /**
136  *  設置子控制項的frame
137  */
138 - (void)settingFrame
139 {
140 
141        // 設置頭像的frame
142     self.iconView.frame = self.weiboFrame.iconF;
143     
144     // 設置昵稱的frame
145         self.nameLabel.frame = self.weiboFrame.nameF;
146     
147     // 設置vip的frame
148        self.vipView.frame = self.weiboFrame.vipF;
149     
150     // 設置正文的frame
151        self.introLabel.frame = self.weiboFrame.introF;
152     
153     // 設置配圖的frame
154 
155     if (self.weiboFrame.weibo.picture) {// 有配圖
156         self.pictureView.frame = self.weiboFrame.pictrueF;
157     }
158 }
159 
160 /**
161  *  計算文本的寬高
162  *
163  *  @param str     需要計算的文本
164  *  @param font    文本顯示的字體
165  *  @param maxSize 文本顯示的範圍
166  *
167  *  @return 文本占用的真實寬高
168  */
169 - (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
170 {
171     NSDictionary *dict = @{NSFontAttributeName : font};
172     // 如果將來計算的文字的範圍超出了指定的範圍,返回的就是指定的範圍
173     // 如果將來計算的文字的範圍小於指定的範圍, 返回的就是真實的範圍
174     CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
175     return size;
176 }
177 
178 @end
複製代碼

NJWeiboFrame.h文件

複製代碼
 1 //  專門用來保存每一行數據的frame, 計算frame
 2 
 3 #import <Foundation/Foundation.h>
 4 @class NJWeibo;
 5 @interface NJWeiboFrame : NSObject
 6 /**
 7  *  頭像的frame
 8  */
 9 @property (nonatomic, assign) CGRect iconF;
10 /**
11  *  昵稱的frame
12  */
13 @property (nonatomic, assign) CGRect nameF;
14 /**
15  *  vip的frame
16  */
17 @property (nonatomic, assign) CGRect vipF;
18 /**
19  *  正文的frame
20  */
21 @property (nonatomic, assign) CGRect introF;
22 /**
23  *  配圖的frame
24  */
25 @property (nonatomic, assign) CGRect pictrueF;
26 /**
27  *  行高
28  */
29 @property (nonatomic, assign) CGFloat cellHeight;
30 
31 /**
32  *  模型數據
33  */
34 @property (nonatomic, strong) NJWeibo *weibo;
35 @end
複製代碼

NJWeiboFrame.m文件

複製代碼
 1 #import "NJWeiboFrame.h"
 2 #import "NJWeibo.h"
 3 #define NJNameFont [UIFont systemFontOfSize:15]
 4 #define NJTextFont [UIFont systemFontOfSize:16]
 5 
 6 
 7 @implementation NJWeiboFrame
 8 
 9 
10 - (void)setWeibo:(NJWeibo *)weibo
11 {
12     _weibo = weibo;
13     
14     // 間隙
15     CGFloat padding = 10;
16     
17     // 設置頭像的frame
18     CGFloat iconViewX = padding;
19     CGFloat iconViewY = padding;
20     CGFloat iconViewW = 30;
21     CGFloat iconViewH = 30;
22     self.iconF = CGRectMake(iconViewX, iconViewY, iconViewW, iconViewH);
23     
24     // 設置昵稱的frame
25     // 昵稱的x = 頭像最大的x + 間隙
26     CGFloat nameLabelX = CGRectGetMaxX(self.iconF) + padding;
27     // 計算文字的寬高
28     CGSize nameSize = [self sizeWithString:_weibo.name font:NJNameFont maxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
29     
30     CGFloat nameLabelH = nameSize.height;
31     CGFloat nameLabelW = nameSize.width;
32     CGFloat nameLabelY = iconViewY + (iconViewH - nameLabelH) * 0.5;
33    self.nameF = CGRectMake(nameLabelX, nameLabelY, nameLabelW, nameLabelH);
34     
35     // 設置vip的frame
36     CGFloat vipViewX = CGRectGetMaxX(self.nameF) + padding;
37     CGFloat vipViewY = nameLabelY;
38     CGFloat vipViewW = 14;
39     CGFloat vipViewH = 14;
40     self.vipF = CGRectMake(vipViewX, vipViewY, vipViewW, vipViewH);
41     
42     // 設置正文的frame
43     CGFloat introLabelX = iconViewX;
44     CGFloat introLabelY = CGRectGetMaxY(self.iconF) + padding;
45     CGSize textSize =  [self sizeWithString:_weibo.text font:NJTextFont maxSize:CGSizeMake(300, MAXFLOAT)];
46     
47     CGFloat introLabelW = textSize.width;
48     CGFloat introLabelH = textSize.height;
49     
50     self.introF = CGRectMake(introLabelX, introLabelY, introLabelW, introLabelH);
51     
52     // 設置配圖的frame
53     CGFloat cellHeight = 0;
54     if (_weibo.picture) {// 有配圖
55         CGFloat pictureViewX = iconViewX;
56         CGFloat pictureViewY = CGRectGetMaxY(self.introF) + padding;
57         CGFloat pictureViewW = 100;
58         CGFloat pictureViewH = 100;
59         self.pictrueF = CGRectMake(pictureViewX, pictureViewY, pictureViewW, pictureViewH);
60         
61         // 計算行高
62         self.cellHeight = CGRectGetMaxY(self.pictrueF) + padding;
63     }else
64     {
65         // 沒有配圖情況下的行高
66         self.cellHeight = CGRectGetMaxY(self.introF) + padding;
67     }
68     
69 }
70 
71 /**
72  *  計算文本的寬高
73  *
74  *  @param str     需要計算的文本
75  *  @param font    文本顯示的字體
76  *  @param maxSize 文本顯示的範圍
77  *
78  *  @return 文本占用的真實寬高
79  */
80 - (CGSize)sizeWithString:(NSString *)str font:(UIFont *)font maxSize:(CGSize)maxSize
81 {
82     NSDictionary *dict = @{NSFontAttributeName : font};
83     // 如果將來計算的文字的範圍超出了指定的範圍,返回的就是指定的範圍
84     // 如果將來計算的文字的範圍小於指定的範圍, 返回的就是真實的範圍
85     CGSize size =  [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
86     return size;
87 }
88 @end
複製代碼

主控制器

NJViewController.m文件

複製代碼
 1 #import "NJViewController.h"
 2 #import "NJWeibo.h"
 3 #import "NJWeiboCell.h"
 4 #import "NJWeiboFrame.h"
 5 
 6 @interface NJViewController ()
 7 @property (nonatomic, strong) NSArray *statusFrames;
 8 @end
 9 
10 @implementation NJViewController
11 
12 #pragma mark - 數據源方法
13 
14 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
15 {
16     return self.statusFrames.count;
17 }
18 
19 
20 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
21 {
22     NJWeiboCell *cell = [NJWeiboCell cellWithTableView:tableView];
23     // 3.設置數據
24    cell.weiboFrame = self.statusFrames[indexPath.row];
25     
26     // 4.返回
27     return cell;
28 }
29 #pragma mark - 懶載入
30 - (NSArray *)statusFrames
31 {
32     if (_statusFrames == nil) {
33         NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"statuses.plist" ofType:nil];
34         NSArray *dictArray = [NSArray arrayWithContentsOfFile:fullPath];
35         NSMutableArray *models = [NSMutableArray arrayWithCapacity:dictArray.count];
36         for (NSDictionary *dict in dictArray) {
37             // 創建模型
38             NJWeibo *weibo = [NJWeibo weiboWithDict:dict];
39             // 根據模型數據創建frame模型
40             NJWeiboFrame *wbF = [[NJWeiboFrame alloc] init];
41             wbF.weibo = weibo;
42             
43             [models addObject:wbF];
44         }
45         self.statusFrames = [models copy];
46     }
47     return _statusFrames;
48 }
49 
50 #pragma mark - 代理方法
51 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
52 {
53     // NSLog(@"heightForRowAtIndexPath");
54     // 取出對應航的frame模型
55     NJWeiboFrame *wbF = self.statusFrames[indexPath.row];
56     NSLog(@"height = %f", wbF.cellHeight);
57     return wbF.cellHeight;
58 }
59 
60 - (BOOL) prefersStatusBarHidden
61 {
62     return YES;
63 }
64 @end
複製代碼

四、補充說明

由於系統提供的tableview可能並不能滿足我們的開發需求,所以經常要求我們能夠自定義tableview。

自定義tableview有兩種方式,一種是使用xib創建,一種是使用純代碼的方式創建。

對於樣式一樣的tableview,通常使用xib進行創建,對於高度不一樣,內容也不完全一致的通常使用純代碼進行自定義。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Android起源與發展: Android操作系統最初在2003年的時候由Andy Rubin開發,主要支持手機。2005年8月由Google收購註資。2007年11月,Google與84家硬體製造商、軟體開發商及電信營運商組建開放手機聯盟共同研發改良Android系統。隨後Google以Apach ...
  • 今天把公司閑置的一臺Mac-mini重裝了下系統感覺用著速度還不錯,平時上班用的機器USB有些問題,所以打算用這台Mac。以往開發用Intellij Idea就夠用,但是這次項目引用的jar包太多,遭遇android Multi-Dex限制,所以用了Android Studio做分包。接下來得先下載 ...
  • 如果資料庫名為:“ifoData.db”,則它的路徑求法為 String pathDatabase=Mcontext.getDatabasePath("ifoData.db").getPath(); 其中Mcontext表示Context內容。 ...
  • GitHub:https://github.com/samvermette/SVProgressHUDSVProgressHUD和MBProgressHUD效果差不多,不過不需要使用協議,同時也不需要聲明實例。直接通過類方法進行調用即可: 可以使用以下方法來顯示狀態: 如果需要明確的進度,則使用以下 ...
  • 完整的開發一個android移動App需要經過從分解需求、架構設計到開發調試、測試、上線發佈等多個階段,在發佈後還會有產品功能上的迭代演進,此外還會面對性能、安全、無線網路質量等多方面的問題。 移動App的產品形態各不相同,有的是內容類,有的是工具類,有的是社交類,所以它們的業務邏輯所偏重的核心技術 ...
  • 源碼如下: 運行結果如下,在屏幕最右邊有一個紅色的P: 源碼解析: 1.首先程式跳轉至LABEL_BEGIN處,jmp LABEL_BEGIN。將ds、es、ss段寄存器全部初始化為當前代碼段。 2.初始化32位代碼段描述符 在實模式下,也就是8086的16位的CPU的定址方式是段x16+偏移,而在 ...
  • activity的佈局 佈局主要有五種: 1.LinearLayout(線性佈局) 可以利用orientation屬性來設置線性佈局是水平還是垂直 2.TableLayout(表格佈局) 3.RelativeLayout(相對佈局) 相對佈局是比較好的佈局方式,它是根據控制項的相對位置來佈局的,這個的 ...
  • 今天愚人節,小伙們,愚人節快樂! 實現一個小功能,滑動菜單,顯示隱藏的功能菜單, 先上圖: 這裡嘗試用了下使用三個方式來實現了這個功能: 1、使用自定義UITableViewCell + UISwipeGestureRecognizer + 代理 實現; 2、使用自定義UITableViewCell ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...