綁定手勢方法

2024-02-07 12:49 更新

通過給各個(gè)組件綁定不同的手勢事件,并設(shè)計(jì)事件的響應(yīng)方式,當(dāng)手勢識別成功時(shí),ArkUI框架將通過事件回調(diào)通知組件手勢識別的結(jié)果。

gesture(常規(guī)手勢綁定方法)

  1. .gesture(gesture: GestureType, mask?: GestureMask)

gesture為通用的一種手勢綁定方法,可以將手勢綁定到對應(yīng)的組件上。

例如,可以將點(diǎn)擊手勢TapGesture通過gesture手勢綁定方法綁定到Text組件上。

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Index {
  5. build() {
  6. Column() {
  7. Text('Gesture').fontSize(28)
  8. // 采用gesture手勢綁定方法綁定TapGesture
  9. .gesture(
  10. TapGesture()
  11. .onAction(() => {
  12. console.info('TapGesture is onAction');
  13. }))
  14. }
  15. .height(200)
  16. .width(250)
  17. }
  18. }

priorityGesture(帶優(yōu)先級的手勢綁定方法)

  1. .priorityGesture(gesture: GestureType, mask?: GestureMask)。

priorityGesture是帶優(yōu)先級的手勢綁定方法,可以在組件上綁定優(yōu)先識別的手勢。

在默認(rèn)情況下,當(dāng)父組件和子組件使用gesture綁定同類型的手勢時(shí),子組件優(yōu)先識別通過gesture綁定的手勢。當(dāng)父組件使用priorityGesture綁定與子組件同類型的手勢時(shí),父組件優(yōu)先識別通過priorityGesture綁定的手勢。

例如,當(dāng)父組件Column和子組件Text同時(shí)綁定TapGesture手勢時(shí),父組件以帶優(yōu)先級手勢priorityGesture的形式進(jìn)行綁定時(shí),優(yōu)先響應(yīng)父組件綁定的TapGesture。

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Index {
  5. build() {
  6. Column() {
  7. Text('Gesture').fontSize(28)
  8. .gesture(
  9. TapGesture()
  10. .onAction(() => {
  11. console.info('Text TapGesture is onAction');
  12. }))
  13. }
  14. .height(200)
  15. .width(250)
  16. // 設(shè)置為priorityGesture時(shí),點(diǎn)擊文本區(qū)域會忽略Text組件的TapGesture手勢事件,優(yōu)先響應(yīng)父組件Column的TapGesture手勢事件
  17. .priorityGesture(
  18. TapGesture()
  19. .onAction(() => {
  20. console.info('Column TapGesture is onAction');
  21. }), GestureMask.IgnoreInternal)
  22. }
  23. }

parallelGesture(并行手勢綁定方法)

  1. .parallelGesture(gesture: GestureType, mask?: GestureMask)

parallelGesture是并行的手勢綁定方法,可以在父子組件上綁定可以同時(shí)響應(yīng)的相同手勢。

在默認(rèn)情況下,手勢事件為非冒泡事件,當(dāng)父子組件綁定相同的手勢時(shí),父子組件綁定的手勢事件會發(fā)生競爭,最多只有一個(gè)組件的手勢事件能夠獲得響應(yīng)。而當(dāng)父組件綁定了并行手勢parallelGesture時(shí),父子組件相同的手勢事件都可以觸發(fā),實(shí)現(xiàn)類似冒泡效果。

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Index {
  5. build() {
  6. Column() {
  7. Text('Gesture').fontSize(28)
  8. .gesture(
  9. TapGesture()
  10. .onAction(() => {
  11. console.info('Text TapGesture is onAction');
  12. }))
  13. }
  14. .height(200)
  15. .width(250)
  16. // 設(shè)置為parallelGesture時(shí),點(diǎn)擊文本區(qū)域會同時(shí)響應(yīng)父組件Column和子組件Text的TapGesture手勢事件
  17. .parallelGesture(
  18. TapGesture()
  19. .onAction(() => {
  20. console.info('Column TapGesture is onAction');
  21. }), GestureMask.IgnoreInternal)
  22. }
  23. }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號