实现效果
通过使用ListItemGroup和AlphabetIndexer两种类型组件,实现带标题分类和右侧导航栏的页面
代码片段
代码架构:
- Models中放实体类
- ViewModel中存放界面操作相关的类
Models/CarItem
export class CarItem {
/**
* 汽车名字集合*/
public CarNameList: string[] = [];
/**
* 所属类型
* */
public Alphabet: string = '';
constructor(carNameList: string[], alphabet: string) {
this.CarNameList = carNameList;
this.Alphabet = alphabet;
}
}
ViewModels/CarViewModel
import { CarItem } from "../Models/CarItem"
/**
* 车辆交互类*/
export class CarViewModel {
/**
* 车辆详细信息集合
* */
public Items: CarItem[] = [];
/**
* 头字母集合*/
public Alphabets: Array<string> = [];
constructor() {
//种子数据初始化
this.Init();
}
/**
* 初始化
*/
public Init(): void {
this.Items.push(new CarItem([
"奥迪1",
"奥迪2",
"奥迪3",
"奥迪4",
"奥迪5",
"奥迪6"
], "A"));
this.Items.push(new CarItem([
"奔驰1",
"奔驰2",
"奔驰3",
"奔驰4",
"奔驰5",
"奔驰6",
"奔驰7",
], "B"));
this.Items.push(new CarItem([
"凯美瑞1",
"凯美瑞2",
"凯美瑞3",
"凯美瑞4",
"凯美瑞5",
"凯美瑞6",
"凯美瑞7",
], "K"));
this.Items.push(new CarItem([
"玛莎拉蒂1",
"玛莎拉蒂2",
"玛莎拉蒂3",
"玛莎拉蒂4",
"玛莎拉蒂5",
"玛莎拉蒂6",
"玛莎拉蒂7",
], "M"));
this.Alphabets.push('A');
this.Alphabets.push('B');
this.Alphabets.push('K');
this.Alphabets.push('M');
}
}
pages/Index
import { CarViewModel } from '../ViewModels/CarViewModel';
import { CarItem } from '../Models/CarItem'
@Entry
@Component
struct Index {
/*
*
* 界面交互类*/
@State CarVM: CarViewModel = new CarViewModel();
@State SelectIndex: number = 0;
listScroller: Scroller = new Scroller();
/**
* 头部控件样式
*/
@Builder
GroupHeader(alphabet: string) {
Text(`${alphabet}`)
.backgroundColor('#fff1f3f5')
.width('100%')
.padding(10)
}
build() {
Column() {
Stack({
alignContent: Alignment.End
}) {
Column() {
List({ scroller: this.listScroller }) {
ForEach(this.CarVM.Items, (car: CarItem, index) => {
ListItemGroup({
header: this.GroupHeader(`${car.Alphabet}`)
}) {
ForEach(car.CarNameList, (name: string, carIndex) => {
ListItem() {
Text(`${name}`)
.fontSize(16)
.width('100%')
.padding(10)
}
})
}
})
}
.height("100%")
.onScrollIndex((selectIndex: number) => {
//滑动时修改
this.SelectIndex = selectIndex;
})
.sticky(StickyStyle.Header) //设置吸顶效果
}.height('100%')
//导航条
AlphabetIndexer({
arrayValue: this.CarVM.Alphabets,
selected: this.SelectIndex
})
.onSelect((index) => {
this.listScroller.scrollToIndex(index);
})
}
}
.width("100%")
.height("100%")
}
}