[TwistedFate]UITableViewCell自定義-02

UITableViewCell自定義

cell分區的行高自適應

採用類方法,是爲了在返回cell的行高時調用

//  計算字符串的高度
+ (CGFloat)cellHeightForModel:(NewsModel *)model{

    //  創建字體大小的字典
    //  字面量初始化
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:16]};

CGRect textRect = [model.summary boundingRectWithSize:CGSizeMake(kScreenWidth - kMargin * 2, 6666) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];

return textRect.size.height;

}

返回cell行高

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

    //  計算高度
    CGFloat labelHeight = [NewsTableViewCell cellHeightForModel:self.newsArray[indexPath.row]];

    //  上邊距 toplabel + 中間距離 + 動態label高度 + 下邊距

    return 20 + 40 + 20 + labelHeight + 40;
}

解決cell的複用性問題

劃出屏幕的cell在被重用時,重新賦值了

在model類裏添加狀態屬性

//  標識選中的狀態
@property (nonatomic, assign) BOOL isSelected;

在數據處理過程中爲模型對象添加狀態屬性值

//  數據處理
- (void)dataProcess{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsData" ofType:@"plist"];

    self.dataDic = [NSMutableDictionary dictionaryWithContentsOfFile:path];

   NSString *key = @"news";

    NSArray *dataArray = self.dataDic[key];

    self.newsArray = [NSMutableArray array];

    for (NSDictionary *dic in dataArray) {

        NewsModel *model = [[NewsModel alloc] init];


        [model setValuesForKeysWithDictionary:dic];

        //  給點擊狀態加一個初值
        model.isSelected = NO;

        [self.newsArray addObject:model];

        [model release];

    }

}

在模型屬性的set方法里根據不同的狀態賦不同的值

- (void)setModel:(NewsModel *)model{

    if (_model != model) {

        [_model release];

        _model = [model retain];

    }

    self.titleLabel.text = model.title;
    self.summaryLabel.text = model.summary;

    //  利用model中的點選狀態解決cell複用的問題
    //  需要背刺被複用的cell 再進行一次與狀態對應對應的賦值
    if (model.isSelected == YES) {

        self.imageV.image = [UIImage imageNamed:@"select"];

    }else{

        self.imageV.image = [UIImage imageNamed:@"cancel"];

    }


    //  計算字符串的高度
    CGFloat summaryHeight = [NewsTableViewCell cellHeightForModel:model];

    //  改變一下label的高度
    self.summaryLabel.height = summaryHeight;

    //  多行顯示
    self.summaryLabel.numberOfLines = 0;
    // 設置字體大小

    self.summaryLabel.font = [UIFont systemFontOfSize:16];

}
發佈了68 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章