• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Grid
2
3The **\<Grid>** component consists of cells formed by rows and columns. You can specify the cells where items are located to form various layouts.
4
5>  **NOTE**
6>
7>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12The **\<Grid>** component accepts only **\<[GridItem](ts-container-griditem.md)>** as its child components.
13
14>  **NOTE**
15>
16>  Below are the rules for calculating the indexes of the child components of **\<Grid>**:
17>
18>  The index increases in ascending order of child components.
19>
20>  In the **if/else** statement, only the child components in the branch where the condition is met participate in the index calculation.
21>
22>  In the **ForEach** or **LazyForEach** statement, the indexes of all expanded subnodes are calculated.
23>
24>  If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated.
25>
26>  The child component that has the **visibility** attribute set to **Hidden** or **None** is included in the index calculation.
27>
28>  The child component that has the **visibility** attribute set to **None** is not displayed, but still takes up the corresponding cell.
29>
30>  The child component that has the **position** attribute set takes up the corresponding cell, and is offset by the distance specified by **position** relative to the upper left corner of the grid. This child component does not scroll with the corresponding cell and is not displayed after the corresponding cell extends beyond the display range of the grid.
31
32## APIs
33
34Grid(scroller?: Scroller)
35
36**Parameters**
37
38| Name  | Type                                   | Mandatory| Description                                                    |
39| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
40| scroller | [Scroller](ts-container-scroll.md#scroller) | No  | Controller, which can be bound to scrollable components.<br>**NOTE**<br>The scroller cannot be bound to other [scrollable components](ts-container-list.md).|
41
42## Attributes
43
44In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
45
46| Name| Type| Description|
47| -------- | -------- | -------- |
48| columnsTemplate | string | Number of columns or minimum column width in the grid. If this attribute is not set, one column will be used.<br>For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.<br>**'repeat(auto-fit, 90px)'** means to automatically work out the number of columns and the actual column width, with the minimum column width of 90.<br>**NOTE**<br>If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.|
49| rowsTemplate | string | Number of rows or minimum row height in the grid. If this attribute is not set, one row will be used.<br>For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.<br>**'repeat(auto-fit, 90px)'** means to automatically work out the number of rows and the actual v, with the minimum row height of 90.<br>**NOTE**<br>If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.|
50| columnsGap | [Length](ts-types.md#length) | Gap between columns.<br>Default value: **0**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
51| rowsGap | [Length](ts-types.md#length) | Gap between rows.<br>Default value: **0**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
52| scrollBar      | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**<br>**NOTE**<br>In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.|
53| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.|
54| scrollBarWidth | string \| number    | Width of the scrollbar. After the width is set, the scrollbar is displayed with the set width in normal state and pressed state.<br>Default value: **4**<br>Unit: vp|
55| cachedCount | number                                   | Number of grid items to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**<br>**NOTE**<br>The number of the grid items to be cached before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns.<br>Grid items that exceed the display and cache range are released.<br>A value less than 0 evaluates to the default value.|
56| editMode <sup>8+</sup>                   | boolean | Whether to enter editing mode. In editing mode, the user can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\<Grid>** component.<br>Default value: **false**|
57| layoutDirection<sup>8+</sup>             | [GridDirection](#griddirection8) | Main axis direction of the grid.<br>Default value: **GridDirection.Row**|
58| maxCount<sup>8+</sup> | number  | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.<br>Default value: **Infinity**<br>**NOTE**<br>If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.<br>A value less than 1 evaluates to the default value.|
59| minCount<sup>8+</sup> | number  | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of rows that can be displayed.<br>Default value: **1**<br>**NOTE**<br>A value less than 1 evaluates to the default value.|
60| cellLength<sup>8+</sup> | number  | When **layoutDirection** is **Row** or **RowReverse**: fixed height per row.<br>When **layoutDirection** is **Column** or **ColumnReverse**: fixed width per column.<br>Default value: size of the first element|
61| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.<br>**NOTE**<br> When mouse frame selection is enabled, you can use the **selected** attribute and the **onSelect** event of the **\<Griditem>** component to obtain the selection status of the component; you can also set the [style](./ts-universal-attributes-polymorphic-style.md) of the component in the selected state (by default, no style is set for the selected state).|
62| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.<br>Default value: **false**|
63| edgeEffect<sup>10+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.<br>Default value: **EdgeEffect.None**<br>|
64| enableScrollInteraction<sup>10+</sup>  |  boolean  |   Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.<br>Default value: **true**     |
65| nestedScroll<sup>10+</sup>                 | [NestedScrollOptions](ts-container-scroll.md#nestedscrolloptions10)         | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.|
66| friction<sup>10+</sup> | number \| [Resource](ts-types.md#resource)    | Friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process.<br>Default value: **0.9** for wearable devices and **0.6** for non-wearable devices<br>**NOTE**<br>A value less than or equal to 0 evaluates to the default value.|
67
68Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\<Grid>** component supports the following layout modes:
69
701. **rowsTemplate** and **columnsTemplate** are both set
71
72- The **\<Grid>** component displays only elements in a fixed number of rows and columns and cannot be scrolled.
73- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
74- If the width and height of a grid are not set, the grid adapts to the size of its parent component by default.
75- The size of the grid rows and columns is the size of the grid content area minus the gap between rows and columns. It is allocated based on the proportion of each row and column.
76- By default, the grid items fill the entire grid.
77
782. Either **rowsTemplate** or **columnsTemplate** is set
79
80- The **\<Grid>** component arranges elements in the specified direction and allows for scrolling to display excess elements.
81- If **columnsTemplate** is set, the component scrolls vertically, the main axis runs vertically, and the cross axis runs horizontally.
82- If **rowsTemplate** is set, the component scrolls horizontally, the main axis runs horizontally, and the cross axis runs vertically.
83- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
84- The cross axis size of the grid is the cross axis size of the grid content area minus the gaps along the cross axis. It is allocated based on the proportion of each row and column.
85- The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid.
86
873. Neither **rowsTemplate** nor **columnsTemplate** is set
88
89- The **\<Grid>** component arranges elements in the direction specified by **layoutDirection**. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**.
90- The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
91- In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
92- When **layoutDirection** is set to **Row**, elements are arranged row by row from left to right. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
93- When **layoutDirection** is set to **Column**, elements are arranged column by column from top to bottom. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
94
95## GridDirection<sup>8+</sup>
96
97| Name  | Description                                  |
98| ------ | -------------------------------------- |
99| Row  | Horizontal layout, where the child components are arranged from left to right as the main axis runs along the rows.|
100| Column | Vertical layout, where the child components are arranged from top to bottom as the main axis runs down the columns.|
101| RowReverse    | Reverse horizontal layout, where the child components are arranged from right to left as the main axis runs along the rows.|
102| ColumnReverse   | Reverse vertical layout, where the child components are arranged from bottom up as the main axis runs down the columns.|
103
104> **NOTE**
105>
106> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\<Grid>** component.
107
108## Events
109
110In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
111
112| Name| Description|
113| -------- | -------- |
114| onScrollIndex(event: (first: number, last<sup>10+</sup>: number) => void) | Triggered when the first or last item displayed in the grid changes. It is triggered once when the grid is initialized.<br>- **first**: index of the first item of the grid.<br>- **last**: index of the last item of the grid.<br>This event is triggered when either of the preceding indexes changes.|
115| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged item.<br>**NOTE**<br>If **void** is returned, the drag operation cannot be performed.<br>This event is triggered when the user long presses a grid item.<br>Drag detection also requires long press, and the event processing mechanism preferentially triggers child component events. Therefore, when **LongPressGesture** is bound to the grid item, the drag operation cannot be performed. In light of this, if both long press and drag operations are required, you can use universal drag events.|
116| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).|
117| onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.|
118| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item leaves the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged item.|
119| onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.<br>- **isSuccess**: whether the dragged item is successfully dropped.|
120| onScrollBarUpdate(event: (index: number, offset: number) => ComputedBarAttribute) | Triggered when the first item displayed in the grid changes. You can use this callback to set the position and length of the scrollbar.<br>- **index**: index of the first item displayed in the grid.<br>- **offset**: offset of the displayed first item relative to the start position of the grid.<br>- **ComputedBarAttribute**: See [ComputedBarAttribute](#computedbarattribute). |
121| onScroll<sup>10+</sup>(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the grid scrolls.<br>- **scrollOffset**: scroll offset of each frame. The offset is positive when the grid is scrolled up and negative when the list is scrolled down.<br>- [scrollState](ts-container-list.md#scrollstate): current scroll state.|
122| onReachStart<sup>10+</sup>(event: () => void)          | Triggered when the grid reaches the start position.<br>**NOTE**<br>This event is triggered once when **initialIndex** is **0** during grid initialization and once when the grid scrolls to the start position. When the grid edge scrolling effect is the spring effect, this event is triggered once when the grid passes the start position and is triggered again when the grid returns to the start position.|
123| onReachEnd<sup>10+</sup>(event: () => void)            | Triggered when the grid reaches the end position.<br>**NOTE**<br>When the grid edge effect is the spring effect, this event is triggered once when the grid passes the end position and is triggered again when the grid returns to the end position.|
124| onScrollFrameBegin<sup>10+</sup>(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the grid starts to scroll. The input parameters indicate the amount by which the grid will scroll. The event handler then works out the amount by which the grid needs to scroll based on the real-world situation and returns the result.<br>\- **offset**: amount to scroll by, in vp.<br>\- **state**: current scrolling state.<br>- **offsetRemain**: actual amount by which the grid scrolls, in vp.<br>This event is triggered when the user starts dragging the grid or the grid starts inertial scrolling. This event is not triggered when the grid rebounds or the scrolling controller is used.<br>**NOTE**<br>If **gridDirection** is set to **Axis.Vertical**, the return value is the amount by which the grid needs to scroll in the vertical direction. If **gridDirection** is set to **Axis.Horizontal**, the return value is the amount by which the grid needs to scroll in the horizontal direction.|
125| onScrollStart<sup>10+</sup>(event: () => void) | Triggered when the grid starts scrolling initiated by the user's finger dragging the grid or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.|
126| onScrollStop<sup>10+</sup>(event: () => void)          | Triggered when the grid stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.|
127
128## ItemDragInfo
129
130| Name        | Type        |   Description        |
131| ---------- | ---------- | ---------- |
132| x | number |  X coordinate of the dragged item.   |
133| y   | number |  Y coordinate of the dragged item.   |
134
135## ComputedBarAttribute
136
137| Name        | Type        |   Description        |
138| ---------- | ---------- | ---------- |
139| totalOffset | number |  Total offset of the grid content relative to the display area.   |
140| totalLength   | number |  Total length of the grid content.   |
141
142## Example
143
144### Example 1
145
146```ts
147// xxx.ets
148@Entry
149@Component
150struct GridExample {
151  @State Number: String[] = ['0', '1', '2', '3', '4']
152  scroller: Scroller = new Scroller()
153
154  build() {
155    Column({ space: 5 }) {
156      Grid() {
157        ForEach(this.Number, (day: string) => {
158          ForEach(this.Number, (day: string) => {
159            GridItem() {
160              Text(day)
161                .fontSize(16)
162                .backgroundColor(0xF9CF93)
163                .width('100%')
164                .height('100%')
165                .textAlign(TextAlign.Center)
166            }
167          }, (day: string) => day)
168        }, (day: string) => day)
169      }
170      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
171      .rowsTemplate('1fr 1fr 1fr 1fr 1fr')
172      .columnsGap(10)
173      .rowsGap(10)
174      .width('90%')
175      .backgroundColor(0xFAEEE0)
176      .height(300)
177
178      Text('scroll').fontColor(0xCCCCCC).fontSize(9).width('90%')
179      Grid(this.scroller) {
180        ForEach(this.Number, (day: string) => {
181          ForEach(this.Number, (day: string) => {
182            GridItem() {
183              Text(day)
184                .fontSize(16)
185                .backgroundColor(0xF9CF93)
186                .width('100%')
187                .height(80)
188                .textAlign(TextAlign.Center)
189            }
190          }, (day: string) => day)
191        }, (day: string) => day)
192      }
193      .columnsTemplate('1fr 1fr 1fr 1fr 1fr')
194      .columnsGap(10)
195      .rowsGap(10)
196      .friction(0.6)
197      .edgeEffect(EdgeEffect.Spring)
198      .scrollBar(BarState.On)
199      .onScrollIndex((first: number) => {
200        console.info(first.toString())
201      })
202      .onScrollBarUpdate((index: number, offset: number) => {
203        return {totalOffset: (index / 5) * (80 + 10) - offset, totalLength: 80 * 5 + 10 * 4}
204      })
205      .width('90%')
206      .backgroundColor(0xFAEEE0)
207      .height(300)
208      Button('next page')
209        .onClick(() => {// Click to go to the next page.
210          this.scroller.scrollPage({ next: true })
211        })
212    }.width('100%').margin({ top: 5 })
213  }
214}
215```
216
217![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif)
218
219### Example 2
220
2211.  Set **editMode\(true\)** to enable the grid to enter editing mode, where the user can drag the grid items.
222
2232.  Through [onItemDragStart](#events), set the image to be displayed during dragging.
224
2253.  Through [onItemDrop](#events), obtain the initial position of the dragged item and the position to which the dragged item will be dropped. Through [onDrag](#events), complete the array position exchange logic.
226
227```ts
228@Entry
229@Component
230struct GridExample {
231  @State numbers: string[] = []
232  scroller: Scroller = new Scroller()
233  @State text: string = 'drag'
234
235  @Builder pixelMapBuilder () { // Style for the drag event.
236    Column() {
237      Text(this.text)
238        .fontSize(16)
239        .backgroundColor(0xF9CF93)
240        .width(80)
241        .height(80)
242        .textAlign(TextAlign.Center)
243    }
244  }
245
246  aboutToAppear() {
247    for (let i = 1;i <= 15; i++) {
248      this.numbers.push(i + '')
249    }
250  }
251
252  changeIndex(index1: number, index2: number) { // Exchange the array position.
253    let temp: string;
254    temp = this.numbers[index1];
255    this.numbers[index1] = this.numbers[index2];
256    this.numbers[index2] = temp;
257  }
258
259  build() {
260    Column({ space: 5 }) {
261      Grid(this.scroller) {
262        ForEach(this.numbers, (day: string) => {
263          GridItem() {
264            Text(day)
265              .fontSize(16)
266              .backgroundColor(0xF9CF93)
267              .width(80)
268              .height(80)
269              .textAlign(TextAlign.Center)
270          }
271        })
272      }
273      .columnsTemplate('1fr 1fr 1fr')
274      .columnsGap(10)
275      .rowsGap(10)
276      .onScrollIndex((first: number) => {
277        console.info(first.toString())
278      })
279      .width('90%')
280      .backgroundColor(0xFAEEE0)
281      .height(300)
282      .editMode(true) // Enable the grid to enter editing mode, where the user can drag the grid items.
283      .onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged.
284        this.text = this.numbers[itemIndex]
285        return this.pixelMapBuilder() // Set the image to be displayed during dragging.
286      })
287      .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid.
288        // If isSuccess is set to false, the item is dropped outside of the grid. If the value of insertIndex is greater than that of length, an item adding event occurs.
289        if (!isSuccess || insertIndex >= this.numbers.length) {
290          return
291        }
292        console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item. insertIndex indicates the position to which the dragged item will be dropped.
293        this.changeIndex(itemIndex, insertIndex)
294      })
295    }.width('100%').margin({ top: 5 })
296  }
297}
298```
299
300Below are some examples.
301
302Below shows how the grid looks when dragging of grid items starts.
303
304![gridDrag](figures/gridDrag.png)
305
306Below shows how the grid looks when dragging of grid items is in progress.
307
308![gridDrag](figures/gridDrag1.png)
309
310Below shows how the grid looks after grid item 1 and grid item 6 swap their positions.
311
312![gridDrag](figures/gridDrag2.png)
313