您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UITableCell 自適應高度:以新聞列表為例的實作

編輯:iOS 開發綜合

做新聞、動態這類列表時,文字長度不一,cell 高度就必須動態計算。常見做法是讓 cell 類自己提供一個「算出高度」的類方法,控制器在 heightForRowAtIndexPath: 裡呼叫它。以下用一個新聞模型把流程串起來。

第一步:建立資料模型

News.h:

#import <Foundation/Foundation.h>

@interface News : NSObject
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *summary;
@end

News.m:

#import "News.h"

@implementation News

- (void)dealloc {
    self.summary = nil;
    self.title = nil;
    [super dealloc];
}

// 當字典裡的 key 找不到同名屬性時會呼叫此方法,重寫它可避免 KVC 轉模型時崩潰
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
}

@end

第二步:在 cell 類裡負責算高度

NewsListCell.h:

#import <UIKit/UIKit.h>

@class News;

@interface NewsListCell : UITableViewCell
@property (nonatomic, retain) News *news;

// 供外部查詢此行應有的高度
+ (CGFloat)cellHigth:(News *)news;
@end

NewsListCell.m 的關鍵在兩個地方:一是把可變高的內容 label 依文字實際高度撐開,二是提供靜態計算方法給 tableView 使用。

#import "NewsListCell.h"
#import "News.h"

@interface NewsListCell ()
{
    UILabel *_titleLabel;
    UILabel *_summarylabel;
}
@end

@implementation NewsListCell

- (void)dealloc {
    self.news = nil;
    [_summarylabel release];
    [_titleLabel release];
    [super dealloc];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setuoSubviews];
    }
    return self;
}

- (void)setuoSubviews {
    // 標題
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 280, 40)];
    _titleLabel.backgroundColor = [UIColor yellowColor];
    _titleLabel.font = [UIFont systemFontOfSize:20.0];
    [self.contentView addSubview:_titleLabel];

    // 內容
    _summarylabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 60, 280, 30)];
    _summarylabel.backgroundColor = [UIColor cyanColor];
    _summarylabel.font = [UIFont systemFontOfSize:17.0];
    _summarylabel.numberOfLines = 0;   // 必須為 0 才能多行
    [self.contentView addSubview:_summarylabel];
}

- (void)setNews:(News *)news {
    if (_news != news) {
        [_news release];
        _news = [news retain];
    }
    _titleLabel.text = news.title;
    _summarylabel.text = news.summary;

    // 依內容實際高度調整 summary label
    CGRect summaryrect = _summarylabel.frame;
    summaryrect.size.height = [[self class] summaryheight:news.summary];
    _summarylabel.frame = summaryrect;
}

// 整行高度 = 固定部分 + 可變部分
+ (CGFloat)cellHigth:(News *)news {
    CGFloat summaryHight = [self summaryheight:news.summary];
    return 10 + 40 + 10 + summaryHight + 20;
}

// 只算文字高度,寬度固定 280
+ (CGFloat)summaryheight:(NSString *)summary {
    // 高度給一個足夠大的值,讓系統依內容回報真實高度
    CGSize contextSize = CGSizeMake(280, 10000);

    // 字體必須與 label 顯示用的字體完全一致,否則算出來會有誤差
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:17.0]};

    CGRect summaryRect = [summary boundingRectWithSize:contextSize
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:attributes
                                              context:nil];
    return summaryRect.size.height;
}

@end

第三步:控制器把高度接上表格

資料從 plist 讀入,轉成 News 物件陣列,然後在兩個資料來源方法裡分別回傳高度與 cell:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *filepath = [[NSBundle mainBundle] pathForResource:@"NewsData" ofType:@"plist"];
    NSDictionary *sourceDic = [NSDictionary dictionaryWithContentsOfFile:filepath];
    _newsArray = [[NSMutableArray alloc] initWithCapacity:50];

    NSArray *sourceArray = sourceDic[@"news"];
    for (NSDictionary *newsDic in sourceArray) {
        News *news = [[News alloc] init];
        [news setValuesForKeysWithDictionary:newsDic];
        [_newsArray addObject:news];
        [news release];
    }

    // 註冊 reuse identifier
    [self.tableView registerClass:[NewsListCell class] forCellReuseIdentifier:kNewsCell];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_newsArray count];
}

// 注意:此時 cell 物件還不存在,所以高度必須靠 cell 的類方法算
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    News *news = _newsArray[indexPath.row];
    return [NewsListCell cellHigth:news];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsListCell *cell = [tableView dequeueReusableCellWithIdentifier:kNewsCell forIndexPath:indexPath];
    cell.news = _newsArray[indexPath.row];
    return cell;
}

這套寫法有兩個必須一致的環節:計算用的字體與 label 的字體要相同,計算用的寬度與 label 的寬度要相同。任一個對不上,就會出現文字被裁掉或多出空白。另外提醒一下,heightForRowAtIndexPath: 會在 cell 建立之前被呼叫,所以高度計算一定要放在類方法這種不依賴實例的地方。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved