Skip to content

List使用

xuwhale6 edited this page Jan 21, 2021 · 2 revisions

List

1. 介绍

  在日常开发中,List是较为常用的组件,它以纵向列表的形式展现用户需要的具体数据和信息

2. 实现

(1)构造方法

--1.无参构造
List()
--2.一个参数构造,传入数据源,将数据源绑定到List
List(tableModel.sourceData)

(2)绑定cell

  • 编写cell布局样式
--编写cell布局样式。List绑定的数据源遍历返回给item,直接使用item为cell赋值。
--cell1
bannerCell(item) {
    ImageView().widthPercent(100)
    .image(item.imgUrl)
    .contentMode(ContentMode.SCALE_ASPECT_FILL)
}
  • 绑定cell
-- bindCell 绑定cell
bindCell(function(item)
        return bannerCell(item) 
    end)
--item的固有属性:
--item.row:返回当前行
--item.section:返回当前section

bindCell(function(item)
        --item.row:返回当前行
        --item.section:返回当前section
        if item.row == 1 then
            --第一行,显示bannerCell
            return bannerCell(item)
        else
            --其他行,显示txtCell
            return txtCell(item)
        end
    end)

(3)绑定数据源

  • 绑定数据源
--1.bindData方法绑定
List().bindData(tableModel.sourceData)
--2.构造方法传入数据源
List(tableModel.sourceData)

附:完整demo如下:

model(tableModel)

--编写cell布局样式。List绑定的数据源遍历返回给item,直接使用item为cell赋值。
--cell1
bannerCell(item) {
    ImageView().widthPercent(100)
    .image(item.imgUrl)
    .contentMode(ContentMode.SCALE_ASPECT_FILL)
}

--cell2
txtCell(item) {
    HStack()
    .padding(5, 10, 5, 10)
    .crossAxis(CrossAxis.CENTER)
    .subs(
        ImageView(item.imgUrl)
        .width(38)
        .height(38)
        .cornerRadius(50)
        .contentMode(ContentMode.SCALE_ASPECT_FILL)
        ,
        Spacer().width(20)
        ,
        Label(item.name)
    )
}

---
--- UI
ui {
    --- layout views
    List()
    .bindCell(function(item)
        --item.row:返回当前行
        --item.section:返回当前section
        if item.row == 1 then
            --第一行,显示bannerCell,设置cell高度100
            --cellHeight(number height),没有设置cell高度时,默认高度自适应。
            return bannerCell(item).cellHeight(100)
        else
            --其他行,显示txtCell,cell高度自适应
            return txtCell(item)
        end
    end)
    .bindData(tableModel.sourceData)

}

---
--- preview
function preview()
    local data = {}
    for i = 1, 10 do
        local temp = {}
        temp.name = "" .. i .. ""
        temp.imgUrl = "https://hbimg.huabanimg.com/7c41bc5871d74c9036932ca9bba76de363727be113b6fd-NApej6_fw658"
        data[i] = temp
    end
    tableModel.sourceData = data
end

3. 常见问题

  • 布局超出:指的是当我们想让List的item条目尽最大限度地占满剩余窗口时可能会出现的界面所有布局高度之和大于父view高度的情况,即溢出父View。
  • 分析原因:.heightPercent(100)表示的含义是将控件的高度设置成父View的总高度
  • 解决办法:通过添加.basis(1)修改控件高度的默认值,将控件的高度设置成父View剩余的可用空间的高度
--1.当整个父View只有一个List控件时,直接为List或在进行数据绑定时设置heightPercent(100),使其填满父View空间;
--2.当整个父View拥有其他控件+List控件时,为List同时设置.heightPercent(100)和.basis(1)属性,表示此时List占满的是父View剩余的可用空间。    
       .bindData(tableModel.sourceData).basis(1)
Clone this wiki locally