HarmonyOS 鸿蒙Next组件拖拽移动位置问题
HarmonyOS 鸿蒙Next组件拖拽移动位置问题
有要学HarmonyOS AI的同学吗,联系我:https://www.itying.com/goods-1206.html
关于HarmonyOS 鸿蒙Next组件拖拽移动位置问题的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。
<markdown _ngcontent-ykx-c237="" class="markdownPreContainer">
我的需求是能够拖动右下角的方框随着我的手一起动,并且在拖动之后能够改变他的位置并记录下改变后的位置坐标,现在有个问题就是可以拖动组件移动可以得到坐标但是他不会跟着我的手动后来给onDragStart加了一个return之后结果本来预想的是右下角那个可以跟着手动结果左上角冒出来一个并且右下这个还存在如何解决,请各位大神指点。
[@State](/user/State) x: number = 0;
[@State](/user/State) y: number = 0;
[@State](/user/State) startX: number = 0;
[@State](/user/State) startY: number = 0;
@Builder area(){
Canvas(this.context)
.width(‘100%’)
.height(‘100%’)
.onReady(()=>{
this.context.fillRect(0,0,100,150)
})
}
Row(){
Row(){
this.area();
}
.position({x: this.x,y: this.y})
.onClick(()=>{
this.x+=10;
this.y+=10;
})
.onDragStart((event: DragEvent) => {
hilog.info(0,“POINT”,'List onDragStart, ’ + ‘X:’ + event.getX() + ‘Y:’ + event.getY())
this.startX = event.getX();
this.startY = event.getY();
hilog.info(0,“POINT”,‘startX:’ + this.startX + ‘startY:’ + this.startY)
return this.area()
})
.onDrop((event: DragEvent) => {
hilog.info(0,“POINT”,'List onDrop, ’ + ‘X:’ + event.getX() + ‘Y:’ + event.getY())
this.x+=(event.getX()-this.startX)
this.y+=(event.getY()-this.startY)
hilog.info(0,“POINT”,‘X:’ + this.x + ‘Y:’ + this.y)
})
.onDragMove((event: DragEvent) => {
hilog.info(0,“POINT”,'List onDragMove, ’ + ‘X:’ + event.getX() + ‘Y:’ + event.getY())
})
}
.width(‘94%’)
.height(‘60%’)
.backgroundImage(this.drawerUrl)
.backgroundImageSize(ImageSize.Cover)
.borderRadius(10)
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>
相关代码如上
</markdown>给拖拽行为提供一个新组件,原组件隐藏。可以认为是两个组件,要拖拽的是组件A,但是拖拽过程看不见组件A的移动,所以要用[@Builder](/user/Builder)构建一个组件B作为拖拽时展示的组件,这时候就会同时存在组件AB,那在拖拽启动时,可以通过Visibility隐藏组件A,拖拽过程中就只展示组件B,拖拽结束后再通过Visibility显示组件A,组件B会自动隐藏。比如:
[@State](/user/State) x: number = 0
[@State](/user/State) y: number = 0
[@State](/user/State) x1: number = 0
[@State](/user/State) y1: number = 0
[@State](/user/State) visible: Visibility = Visibility.Visible;
[@Builder](/user/Builder) myBuilder() {
Text('拖拽中')
}
build() {
Column() {
Text('长按拖拽')
.position({ x: this.x1, y: this.y1 })
.visibility(this.visible)
.onDragStart((event: DragEvent) => {
this.visible = Visibility.Hidden
this.x = event.getX()
this.y = event.getY()
return this.myBuilder()
})
.onDrop((event: DragEvent) => {
this.visible = Visibility.Visible
this.x1 += event.getX() - this.x
this.y1 += event.getY() - this.y
})
}.width('100%')
.height('100%')
}
这种用onTouch 吧