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

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

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

2020-07-26 03:22:57
字體:
供稿:網(wǎng)友

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

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

20164992950112.png (283×53)

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

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

20164993051610.png (469×203)

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

20164993110344.png (489×377)

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

20164993126002.png (237×183)

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

20164993147213.png (393×167)

單擊Next,輸入類名CustomCell,Subclass of選擇UITableViewCell:

20164993206913.png (475×77)

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

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

20164993227183.png (600×167)

單擊Next,選擇iPhone,再單擊Next,輸入名稱為CustomCell,選擇好位置:

20164993247395.png (385×282)

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

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

20164993306795.png (692×271)

選中新加的控件,打開Identity Inspector,選擇Class為CustomCell;然后打開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:

20164993327862.png (357×100)

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

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

20164993346980.png (221×179)

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

7、打開CustomCell.h,添加屬性:

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

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

8、打開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)于重寫了各個(gè)set函數(shù),從而當(dāng)執(zhí)行賦值操作時(shí),會(huì)執(zhí)行我們自己寫的函數(shù)。

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

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

20164993418241.png (474×295)

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

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

10、打開ViewController.h,向其中添加代碼:

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

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

11、打開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)行:

20164993439292.jpg (315×450)

二、如何重用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) {//說明可重用隊(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è)問題還是比較頭疼的,下面這個(gè)函數(shù)肯定要用到
復(fù)制代碼 代碼如下:

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

經(jīng)過實(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中訪問這個(gè)私有變量

通過上述方式可以動(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ì)算出來了,那么如果自定義一個(gè)UITableViewCell,并且其內(nèi)部的UILabel高度可變的話
也是可以實(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邏輯外面做。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沂源县| 巴林右旗| 循化| 盐城市| 抚顺市| 玉山县| 绥化市| 普兰县| 聂拉木县| 鸡西市| 平谷区| 临沧市| 微山县| 黄大仙区| 盐边县| 兴和县| 平顶山市| 海口市| 昌都县| 固阳县| 罗平县| 林周县| 白水县| 滕州市| 库车县| 航空| 长春市| 阿拉尔市| 锡林浩特市| 汝城县| 巍山| 新密市| 灵武市| 乌审旗| 阿荣旗| 科技| 色达县| 德庆县| 广德县| 阳高县| 河东区|