参考下述demo:@Entry @Component struct GridDemo { @State numbers: string[] = [] scroller: Scroller = new Scroller() @State text: string = 'drag' @State currentIndex: number = -1 @State x: number = 0 @State y: number = 0 @State itemWidth: number = 0 @Builder pixelMapBuilder() { //拖拽过程样式 Column() { Text(this.text) .fontSize(16) .backgroundColor(0xF9CF93) .width(this.itemWidth) .height(80) .textAlign(TextAlign.Center) } } aboutToAppear() { for (let i = 1; i <= 15; i++) { this.numbers.push(i + '') } } changeIndex(index1: number, index2: number) { //交换数组位置 let temp: string; temp = this.numbers[index1]; this.numbers[index1] = this.numbers[index2]; this.numbers[index2] = temp; } setCurrentIndex(index: number) { if (index === this.numbers.length) return this.x = this.scroller.getItemRect(index).x this.y = this.scroller.getItemRect(index).y console.log('this.x', this.x) console.log('this.y', this.y) this.currentIndex = index } build() { Column({ space: 5 }) { Column() { Column() .width(this.itemWidth) .height(80) .position({ x: this.x, y: this.y }) .zIndex(2) .visibility(this.currentIndex === -1 ? Visibility.Hidden : Visibility.Visible) .border({ width: 2, style: { left: BorderStyle.Dotted, right: BorderStyle.Dotted, top: BorderStyle.Dotted, bottom: BorderStyle.Dotted }, color: Color.Gray }) .hitTestBehavior(HitTestMode.None) Grid(this.scroller) { ForEach(this.numbers, (day: string, index: number) => { GridItem() { Text(day) .fontSize(16) .backgroundColor(0xF9CF93) .width('100%') .height(80) .textAlign(TextAlign.Center) } }) } .columnsTemplate('1fr 1fr') .columnsGap(10) .rowsGap(10) .onScrollIndex((first: number) => { console.info(first.toString()) }) .width('90%') .backgroundColor(0xFAEEE0) .supportAnimation(true) // .height(300) .editMode(true) //设置Grid是否进入编辑模式,进入编辑模式可以拖拽Grid组件内部GridItem .onItemDragStart((event: ItemDragInfo, itemIndex: number) => { //第一次拖拽此事件绑定的组件时,触发回调。 this.text = this.numbers[itemIndex] this.itemWidth = this.scroller.getItemRect(itemIndex).width this.setCurrentIndex(itemIndex) return this.pixelMapBuilder() //设置拖拽过程中显示的图片。 }) .onItemDragMove((event: ItemDragInfo, itemIndex: number, insertIndex: number) => { this.setCurrentIndex(insertIndex) }) .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。 // isSuccess=false时,说明drop的位置在grid外部;insertIndex > length时,说明有新增元素的事件发生 if (!isSuccess || insertIndex >= this.numbers.length) { return } console.info('beixiang' + itemIndex + '', insertIndex + '') //itemIndex拖拽起始位置,insertIndex拖拽插入位置 this.currentIndex = -1 this.changeIndex(itemIndex, insertIndex) }) } }.width('100%').margin({ top: 5 }) } }
参考下述demo: