Skip to content

Tutorial 2: Create Table Cell with xml layout

zhenglibao edited this page Jun 19, 2019 · 2 revisions

Write xml layout

The following is a demo:

<?xml version="1.0" encoding="utf-8"?>
<UIView
    layout="flexDirection: row,margin:8" attr="bgColor:white">
    <UIImageView layout="width:40,height:40,marginLeft:10,marginRight:10"  attr="source:addnewtype.png"/>
    <UIView
        layout="flex:1">
        <UIView
            layout="flexDirection:row">
            <UILabel name="name" attr="fontSize:14,color:#333333,text:你的名字,linesNum:1"/>
            <UILabel name="type" layout="flex:1" attr="fontSize:14,color:#999999,text:一般类型,linesNum:1"/>
            <UILabel name="date" attr="fontSize:14,color:#999999,text:5-11,linesNum:1"/>
        </UIView>
        <UIView layout="height:8"/>
        <UILabel name="title"
        attr="fontSize:18,color:#333333,text:title,linesNum:1"/>
        <UIView layout="height:8"/>
        <UILabel name="content" layout="width:100%"
        attr="fontSize:14,color:#333333,text:aaa,linesNum:0,lineBreakMode:truncatingTail"/>
        <UIView layout="height:8"/>
    </UIView>
</UIView> 

Actually, there is no difference than view controller layout except that it will be used for tabel cell.

Derive table cell class from FlexBaseTableCell:

@interface TestTableCell : FlexBaseTableCell
{
    UILabel* _name;
    UILabel* _model;
    UILabel* _sn;
    UILabel* _updatedBy;

    UIImageView* _return;
}
@end
@implementation TestTableCell
@end

Use table cell in view UITableView delegate

  • In cellForRowAtIndexPath callback, call initWithFlex to build cell. In heightForRowAtIndexPath, call heightForWidth to calculate height
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    static NSString *identifier = @"TestTableCellIdentifier";
    TestTableCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[TestTableCell alloc]initWithFlex:nil reuseIdentifier:identifier];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_cell==nil){
        _cell = [[TestTableCell alloc]initWithFlex:nil reuseIdentifier:nil];
    }
    return [_cell heightForWidth:_table.frame.size.width];
}

That's all.

注意:

如果xml中最外层的view设置了flex:1属性,则表示匹配父窗口大小,此时将不能正确计算cell的高度,一定要将xml最外层的view设置为由内容撑开。

Clone this wiki locally