国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > iOS > 正文

全面解析iOS應(yīng)用中自定義UITableViewCell的方法

2019-10-21 18:54:56
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
這篇文章主要介紹了iOS應(yīng)用開(kāi)發(fā)中自定義UITableViewCell的方法,示例為傳統(tǒng)的Obejective-C語(yǔ)言,需要的朋友可以參考下
 

有時(shí)候我們需要自己定義UITableViewCell的風(fēng)格,其實(shí)就是向行中添加子視圖。添加子視圖的方法主要有兩種:使用代碼以及從.xib文件加載。當(dāng)然后一種方法比較直觀。

一、基本用法
我們這次要自定義一個(gè)Cell,使得它像QQ好友列表的一行一樣:左邊是一張圖片,圖片的右邊是三行標(biāo)簽:

iOS應(yīng)用,UITableViewCell

當(dāng)然,我們不會(huì)搞得這么復(fù)雜,只是有點(diǎn)意思就行。

1、運(yùn)行Xcode 4.2,新建一個(gè)Single View Application,名稱(chēng)為Custom Cell:

iOS應(yīng)用,UITableViewCell

2、將圖片資源導(dǎo)入到工程。為此,我找了14張50×50的.png圖片,名稱(chēng)依次是1、2、……、14,放在一個(gè)名為Images的文件夾中。將此文件夾拖到工程中,在彈出的窗口中選中Copy items into…

iOS應(yīng)用,UITableViewCell

添加完成后,工程目錄如下:

iOS應(yīng)用,UITableViewCell

3、創(chuàng)建一個(gè)UITableViewCell的子類(lèi):選中Custom Cell目錄,依次選擇File — New — New File,在彈出的窗口,左邊選擇Cocoa Touch,右邊選擇Objective-C class:

iOS應(yīng)用,UITableViewCell

單擊Next,輸入類(lèi)名CustomCell,Subclass of選擇UITableViewCell:

iOS應(yīng)用,UITableViewCell

之后選擇Next和Create,就建立了兩個(gè)文件:CustomCell.h和CustomCell.m。

4、創(chuàng)建CustomCell.xib:依次選擇File — New — New File,在彈出的窗口,左邊選擇User Interface,右邊選擇Empty:

iOS應(yīng)用,UITableViewCell

單擊Next,選擇iPhone,再單擊Next,輸入名稱(chēng)為CustomCell,選擇好位置:

iOS應(yīng)用,UITableViewCell

單擊Create,這樣就創(chuàng)建了CustomCell.xib。

5、打開(kāi)CustomCell.xib,拖一個(gè)Table View Cell控件到面板上:

iOS應(yīng)用,UITableViewCell

選中新加的控件,打開(kāi)Identity Inspector,選擇Class為CustomCell;然后打開(kāi)Size Inspector,調(diào)整高度為60。

6、向新加的Table View Cell添加控件:拖放一個(gè)ImageView控件到左邊,并設(shè)置大小為50×50。然后在ImageView右邊添加三個(gè)Label,設(shè)置標(biāo)簽字號(hào),最上邊的是14,其余兩個(gè)是12:

iOS應(yīng)用,UITableViewCell

接下來(lái)向CustomCell.h添加Outlet映射,將ImageView與三個(gè)Label建立映射,名稱(chēng)分別為imageView、nameLabel、decLabel以及l(fā)ocLable,分別表示頭像、昵稱(chēng)、個(gè)性簽名,地點(diǎn)。

選中Table View Cell,打開(kāi)Attribute Inspector,將Identifier設(shè)置為CustomCellIdentifier:

iOS應(yīng)用,UITableViewCell

為了充分使用這些標(biāo)簽,還要自己創(chuàng)建一些數(shù)據(jù),存在plist文件中,后邊會(huì)做。

7、打開(kāi)CustomCell.h,添加屬性:

復(fù)制代碼代碼如下:

@property (copy, nonatomic) UIImage *image;
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *dec;
@property (copy, nonatomic) NSString *loc;

8、打開(kāi)CustomCell.m,向其中添加代碼:

 

8.1 在@implementation下面添加代碼:

復(fù)制代碼代碼如下:

@synthesize image;
@synthesize name;
@synthesize dec;
@synthesize loc;

8.2 在@end之前添加代碼:
復(fù)制代碼代碼如下:

- (void)setImage:(UIImage *)img {
    if (![img isEqual:image]) {
        image = [img copy];
        self.imageView.image = image;
    }
}

 

-(void)setName:(NSString *)n {
    if (![n isEqualToString:name]) {
        name = [n copy];
        self.nameLabel.text = name;
    }
}

-(void)setDec:(NSString *)d {
    if (![d isEqualToString:dec]) {
        dec = [d copy];
        self.decLabel.text = dec;
    }
}

-(void)setLoc:(NSString *)l {
    if (![l isEqualToString:loc]) {
        loc = [l copy];
        self.locLabel.text = loc;
    }
}


這相當(dāng)于重寫(xiě)了各個(gè)set函數(shù),從而當(dāng)執(zhí)行賦值操作時(shí),會(huì)執(zhí)行我們自己寫(xiě)的函數(shù)。

 

好了,現(xiàn)在自己定義的Cell已經(jīng)可以使用了。

不過(guò)在此之前,我們先新建一個(gè)plist,用于存儲(chǔ)想要顯示的數(shù)據(jù)。建立plist文件的方法前面的文章有提到。我們建好一個(gè)friendsInfo.plist,往其中添加數(shù)據(jù)如下:

iOS應(yīng)用,UITableViewCell

注意每個(gè)節(jié)點(diǎn)類(lèi)型選擇。

9、打開(kāi)ViewController.xib,拖一個(gè)Table View到視圖上,并將Delegate和DataSource都指向File' Owner,就像上一篇文章介紹的一樣。

10、打開(kāi)ViewController.h,向其中添加代碼:

復(fù)制代碼代碼如下:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) NSArray *dataList;
@property (strong, nonatomic) NSArray *imageList;
@end

11、打開(kāi)ViewController.m,添加代碼:

 

11.1 在首部添加:

復(fù)制代碼代碼如下:

#import "CustomCell.h"

11.2 在@implementation后面添加代碼:
復(fù)制代碼代碼如下:

@synthesize dataList;
@synthesize imageList;

11.3 在viewDidLoad方法中添加代碼:
復(fù)制代碼代碼如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //加載plist文件的數(shù)據(jù)和圖片
    NSBundle *bundle = [NSBundle mainBundle];
    NSURL *plistURL = [bundle URLForResource:@"friendsInfo" withExtension:@"plist"];
    
    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
    
    NSMutableArray *tmpDataArray = [[NSMutableArray alloc] init];
    NSMutableArray *tmpImageArray = [[NSMutableArray alloc] init];
    for (int i=0; i<[dictionary count]; i++) {
        NSString *key = [[NSString alloc] initWithFormat:@"%i", i+1];
        NSDictionary *tmpDic = [dictionary objectForKey:key];
        [tmpDataArray addObject:tmpDic];
        
        NSString *imageUrl = [[NSString alloc] initWithFormat:@"%i.png", i+1];
        UIImage *image = [UIImage imageNamed:imageUrl];
        [tmpImageArray addObject:image];
    }
    self.dataList = [tmpDataArray copy];
    self.imageList = [tmpImageArray copy];
}

11.4 在ViewDidUnload方法中添加代碼:
復(fù)制代碼代碼如下:

self.dataList = nil;
self.imageList = nil;

11.5 在@end之前添加代碼:
復(fù)制代碼代碼如下:

#pragma mark -
#pragma mark Table Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataList count];
}

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
    
    static BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:CustomCellIdentifier];
        nibsRegistered = YES;
    }
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
 
    
    NSUInteger row = [indexPath row];
    NSDictionary *rowData = [self.dataList objectAtIndex:row];
    
    cell.name = [rowData objectForKey:@"name"];
    cell.dec = [rowData objectForKey:@"dec"];
    cell.loc = [rowData objectForKey:@"loc"];
    cell.image = [imageList objectAtIndex:row];
     
    return cell;
}

#pragma mark Table Delegate Methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.0;
}

- (NSIndexPath *)tableView:(UITableView *)tableView 
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    return nil;
}


12、運(yùn)行:

 

iOS應(yīng)用,UITableViewCell

 

二、如何重用UITableviewCell

重用的目的是為了減少內(nèi)存消耗,假如有1千個(gè)cell,如果不重用,那么每一次滑動(dòng)都得重新

alloc 很多很多的cell,耗費(fèi)內(nèi)存,同時(shí)屏幕會(huì)出現(xiàn)不連續(xù)的現(xiàn)象,晃眼睛。

重用cell很簡(jiǎn)單,在創(chuàng)建cell的時(shí)候,使用

alloc initwithtableviewCellStyle:reuseIdentifer這個(gè)接口創(chuàng)建cell實(shí)例,而非使用alloc initwithFrame

使用前者表示該cell可重用,identifer使用一個(gè)固定的NSString即可

代碼如下:

復(fù)制代碼代碼如下:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    static NSString *CellIdentifier = @"Cell";  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];//首先從可重用隊(duì)列里面彈出一個(gè)cell  
    if (cell == nil) {//說(shuō)明可重用隊(duì)列里面并cell,此時(shí)需要重新創(chuàng)建cell實(shí)例,采用下面方法  
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;    
    }else{//此時(shí)表示有可重用cell,直接返回即可  
        NSLog(@"cell 重用啦");  
    }      
    return cell;  
}  

三、如何如何動(dòng)態(tài)調(diào)整cell的高度?
這個(gè)問(wèn)題還是比較頭疼的,下面這個(gè)函數(shù)肯定要用到
復(fù)制代碼代碼如下:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

經(jīng)過(guò)實(shí)踐之后發(fā)現(xiàn),可以在創(chuàng)建cell或者重用cell的時(shí)候,設(shè)置其frame

 

比如cell.frame=CGRectMake(0,0,320,450);

這個(gè)代碼會(huì)有效,同時(shí)在下面這個(gè)函數(shù)里面

使用:

復(fù)制代碼代碼如下:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    
    NSLog(@"當(dāng)前是第%ld行",(long)indexPath.row);  
      
    UITableViewCell *myCell=[self tableView:tableView cellForRowAtIndexPath:indexPath];//獲取當(dāng)前indexPath中的cell實(shí)例  
    if( myCell == nil ){  
        return 0;  
          
    }else{  
          
        NSLog(@"%f",myCell.frame.size.height);  
        return  myCell.frame.size.height;  
          
    }  
    return 0;  
      
}  

上面獲取當(dāng)前indexPath的cell實(shí)例會(huì)重新申請(qǐng)建立一個(gè)實(shí)例(意思是個(gè)cell實(shí)際要?jiǎng)?chuàng)建兩個(gè)實(shí)例)
這樣的目的是為了獲取cell的frame,如果不這樣做也可以在第一部分創(chuàng)建cell的時(shí)候,將cell的frame保存在一個(gè)私有

 

變量中,在heightForRowAtIndexPath中訪(fǎng)問(wèn)這個(gè)私有變量

通過(guò)上述方式可以動(dòng)態(tài)改變UITableViewCell的高度

四、對(duì)于一個(gè)UILabel,根據(jù)其內(nèi)容計(jì)算CGRect

首先要設(shè)置UILable的font,比如

tmLabel.font=[UIFont  systemFontOfSize:14.0f];

然后使用boundingRectOfSize計(jì)算出該尺寸對(duì)應(yīng)的矩形大小,代碼如下:

復(fù)制代碼代碼如下:

NSDictionary *attrDic=@{NSFontAttributeName:[UIFont systemFontOfSize:12.0f]};  
CGSize labelSize=[text boundingRectWithSize:CGSizeMake(320, 990)  
                                    options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading  
                                 attributes:attrDic context:nil].size;  
  
CGRect labelRect=CGRectMake(0, 0, labelSize.width, labelSize.height);
  
 現(xiàn)在UILable的rect都可以被計(jì)算出來(lái)了,那么如果自定義一個(gè)UITableViewCell,并且其內(nèi)部的UILabel高度可變的話(huà)
也是可以實(shí)現(xiàn)的

 

五、內(nèi)部含有可變高度的UILabel的UITableViewCell
如果還有其他控件,比如UIButton等等,也是一樣的。

這些控件在實(shí)例化的時(shí)候,設(shè)置frame為CGRectZero, 然后分別計(jì)算各自的高度和尺寸

使用cell.contentview addSubview 的方式,將這些子空間添加到cell中。重新計(jì)算cell的frame時(shí)

也需要把這些控件的frame累加上。上代碼:

復(fù)制代碼代碼如下:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
  
    static NSString *CellIdentifier = @"Cell";  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
      
    if (cell == nil) {  
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;  
          
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];  
        label.tag = 1;  
        label.lineBreakMode = NSLineBreakByCharWrapping;  
        label.highlightedTextColor = [UIColor whiteColor];  
        label.numberOfLines = 0;  
        label.opaque = NO; // 選中Opaque表示視圖后面的任何內(nèi)容都不應(yīng)該繪制  
        label.font=[UIFont systemFontOfSize:12.0f];  
        label.backgroundColor = [UIColor grayColor];  
        [cell.contentView addSubview:label];  
          
        UIButton *tmpButton=[[UIButton alloc]initWithFrame:CGRectZero];  
        tmpButton.tag=2;  
        tmpButton.backgroundColor=[UIColor cyanColor];  
        [cell.contentView addSubview:tmpButton];  
        tmpButton.opaque=NO;  
        [tmpButton setTitle:@"nihao" forState:UIControlStateNormal];  
        [tmpButton setTitleColor:[UIColor whiteColor ]forState:UIControlStateHighlighted];  
        [tmpButton addTarget:self action:@selector(tmpButtonHandler:) forControlEvents:UIControlEventTouchUpInside];  
          
    }else{  
        NSLog(@"cell 重用啦");  
    }  
      
        UILabel *tmpLabel=(UILabel *)[cell viewWithTag:1];  
        NSString *text=[tmpArray objectAtIndex:indexPath.row];  
        tmpLabel.text=text;  
          
        UIButton *tmpButton=(UIButton *)[cell viewWithTag:2];  
          
        NSDictionary *attrDic=@{NSFontAttributeName:[UIFont systemFontOfSize:12.0f]};  
        CGSize labelSize=[text boundingRectWithSize:CGSizeMake(320, 990)  
                                            options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading  
                                         attributes:attrDic context:nil].size;  
          
        CGRect labelRect=CGRectMake(0, 0, labelSize.width, labelSize.height);//計(jì)算UILabel的rect  
        [tmpLabel setFrame:labelRect];  
        [tmpButton setFrame:CGRectMake(0, labelSize.height+1, 100, 50)];//計(jì)算UIButton 子控件的rect  
        [cell setFrame:CGRectMake(0, 0, labelSize.width, labelSize.height+50+1)];//cell的frame是以上兩個(gè)子控件之和  
    
    return cell;  
}  

為何不再創(chuàng)建時(shí)設(shè)置frame,而是在if和else邏輯后面?
重用cell的時(shí)候,從重用cell隊(duì)列里面取出的cell,其內(nèi)容(UILabel)是之前的cell內(nèi)容,需要重新填充UILabel并且重新計(jì)算

 

整個(gè)cell的frame并設(shè)置其frame。而創(chuàng)建cell的時(shí)候也需要設(shè)置frame,所以這兩個(gè)邏輯重復(fù),直接放在if else邏輯外面做。



注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到IOS開(kāi)發(fā)頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 共和县| 深圳市| 翁牛特旗| 明星| 彭水| 秦皇岛市| 中卫市| 德令哈市| 仙游县| 博爱县| 晋城| 荆州市| 昌邑市| 雷州市| 无极县| 余江县| 荣成市| 铜山县| 泸水县| 华蓥市| 鹤峰县| 阳城县| 永安市| 韶山市| 五大连池市| 阳城县| 民权县| 德阳市| 金溪县| 绥芬河市| 中方县| 内丘县| 盐山县| 广宁县| 天祝| 金溪县| 织金县| 新乐市| 山西省| 衡水市| 虹口区|