未验证 提交 c533cf0b 编写于 作者: O openharmony_ci 提交者: Gitee

!11311 翻译完成 9945/11009

Merge pull request !11311 from ester.zhou/TR-11009
# Rendering Control
ArkTS provides conditional rendering and loop rendering. Conditional rendering can render state-specific UI content based on the application status. Loop rendering iteratively obtains data from the data source and creates the corresponding component during each iteration.
## Conditional Rendering
Use **if/else** for conditional rendering.
> **NOTE**
>
> - State variables can be used in the **if/else** statement.
>
> - The **if/else** statement can be used to implement rendering of child components.
>
> - The **if/else** statement must be used in container components.
>
> - Some container components limit the type or number of subcomponents. When **if/else** is placed in these components, the limitation applies to components created in **if/else** statements. For example, when **if/else** is used in the **\<Grid>** container component, whose child components can only be **\<GridItem>**, only the **\<GridItem>** component can be used in the **if/else** statement.
```ts
Column() {
if (this.count < 0) {
Text('count is negative').fontSize(14)
} else if (this.count % 2 === 0) {
Text('count is even').fontSize(14)
} else {
Text('count is odd').fontSize(14)
}
}
```
## Loop Rendering
You can use **ForEach** to obtain data from arrays and create components for each data item.
```
ForEach(
arr: any[],
itemGenerator: (item: any, index?: number) => void,
keyGenerator?: (item: any, index?: number) => string
)
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| arr | any[] | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.|
| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.|
> **NOTE**
>
> - **ForEach** must be used in container components.
>
> - The generated child components should be allowed in the parent container component of **ForEach**.
>
> - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the array. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }),
> item => Text(`${item.i}. item.data.label`),
> item => item.data.id.toString())
> ```
## Example
```ts
// xxx.ets
@Entry
@Component
struct MyComponent {
@State arr: number[] = [10, 20, 30]
build() {
Column({ space: 5 }) {
Button('Reverse Array')
.onClick(() => {
this.arr.reverse()
})
ForEach(this.arr, (item: number) => {
Text(`item value: ${item}`).fontSize(18)
Divider().strokeWidth(2)
}, (item: number) => item.toString())
}
}
}
```
![forEach1](figures/forEach1.gif)
## Lazy Loading
You can use **LazyForEach** to iterate over provided data sources and create corresponding components during each iteration.
```ts
LazyForEach(
dataSource: IDataSource,
itemGenerator: (item: any) => void,
keyGenerator?: (item: any) => string
): void
interface IDataSource {
totalCount(): number;
getData(index: number): any;
registerDataChangeListener(listener: DataChangeListener): void;
unregisterDataChangeListener(listener: DataChangeListener): void;
}
interface DataChangeListener {
onDataReloaded(): void;
onDataAdd(index: number): void;
onDataMove(from: number, to: number): void;
onDataDelete(index: number): void;
onDataChange(index: number): void;
}
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | --------------------- | ---- | ------------------------------------------------------------ |
| dataSource | IDataSource | Yes | Object used to implement the **IDataSource** API. You need to implement related APIs. |
| itemGenerator | (item: any) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.|
### Description of IDataSource
| Name | Description |
| ------------------------------------------------------------ | ---------------------- |
| totalCount(): number | Obtains the total number of data records. |
| getData(index: number): any | Obtains the data corresponding to the specified index. |
| registerDataChangeListener(listener:DataChangeListener): void | Registers a listener for data changes.|
| unregisterDataChangeListener(listener:DataChangeListener): void | Deregisters a listener for data changes.|
### Description of DataChangeListener
| Name | Description |
| -------------------------------------------------------- | -------------------------------------- |
| onDataReloaded(): void | Invoked when all data is reloaded. |
| onDataAdded(index: number): void (deprecated) | Invoked when data is added to the position indicated by the specified index. |
| onDataMoved(from: number, to: number): void (deprecated) | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDeleted(index: number): void (deprecated) | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChanged(index: number): void (deprecated) | Invoked when data in the position indicated by the specified index is changed. |
| onDataAdd(index: number): void 8+ | Invoked when data is added to the position indicated by the specified index. |
| onDataMove(from: number, to: number): void 8+ | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDelete(index: number): void 8+ | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChange(index: number): void 8+ | Invoked when data in the position indicated by the specified index is changed. |
## Example
```ts
// xxx.ets
class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = []
public totalCount(): number {
return 0
}
public getData(index: number): any {
return undefined
}
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
console.info('add listener')
this.listeners.push(listener)
}
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const pos = this.listeners.indexOf(listener);
if (pos >= 0) {
console.info('remove listener')
this.listeners.splice(pos, 1)
}
}
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded()
})
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index)
})
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index)
})
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index)
})
}
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMove(from, to)
})
}
}
class MyDataSource extends BasicDataSource {
// Initialize the data list.
private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png']
public totalCount(): number {
return this.dataArray.length
}
public getData(index: number): any {
return this.dataArray[index]
}
public addData(index: number, data: string): void {
this.dataArray.splice(index, 0, data)
this.notifyDataAdd(index)
}
public pushData(data: string): void {
this.dataArray.push(data)
this.notifyDataAdd(this.dataArray.length - 1)
}
}
@Entry
@Component
struct MyComponent {
private data: MyDataSource = new MyDataSource()
build() {
List({ space: 3 }) {
LazyForEach(this.data, (item: string) => {
ListItem() {
Row() {
Image(item).width(50).height(50)
Text(item).fontSize(20).margin({ left: 10 })
}.margin({ left: 10, right: 10 })
}
.onClick(() => {
// The count increases by one each time the list is clicked.
this.data.pushData('/path/image' + this.data.totalCount() + '.png')
})
}, item => item)
}
}
}
```
> **NOTE**
>
> - **LazyForEach** must be used in the container component. Currently, only the **\<List>**, **\<Grid>**, and **\<Swiper>** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time.
>
> - **LazyForEach** must create and only one child component in each iteration.
>
> - The generated child components must be allowed in the parent container component of **LazyForEach**.
>
> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement.
>
> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the data source. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)),
> item => item.data.id.toString())
> ```
![lazyForEach](figures/lazyForEach.gif)
......@@ -10,10 +10,10 @@ You can set the background of a component.
| Name| Type| Description|
| -------- | -------- | -------- |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. |
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.<br>**src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.|
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.|
| backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>Default value: **ImageSize.Auto**|
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.<br>Default value:<br>**{<br>x: 0,<br>y: 0<br>}** |
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} <br> When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.|
## Example
......
......@@ -11,8 +11,8 @@ Layout constraints refer to constraints on the aspect ratio and display priority
| Name | Type | Description |
| --------------- | ------ | ---------------------------------------- |
| aspectRatio | number | Aspect ratio of the component. |
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.|
| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height. |
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components. |
## Example
......@@ -22,29 +22,32 @@ Layout constraints refer to constraints on the aspect ratio and display priority
@Entry
@Component
struct AspectRatioExample {
private children : string[] = ['1', '2', '3', '4', '5', '6']
private children: string[] = ['1', '2', '3', '4', '5', '6']
build() {
Column({space: 20}) {
Column({ space: 20 }) {
Text('using container: row').fontSize(14).fontColor(0xCCCCCC).width('100%')
Row({space: 10}) {
Row({ space: 10 }) {
ForEach(this.children, (item) => {
// Component width = Component height x 1.5 = 90
Text(item)
.backgroundColor(0xbbb2cb)
.fontSize(20)
.aspectRatio(1.5)
.height(60)
// Component height = Component width/1.5 = 60/1.5 = 40
Text(item)
.backgroundColor(0xbbb2cb)
.fontSize(20)
.aspectRatio(1.5)
.width(60)
}, item=>item)
}, item => item)
}
.size({width: "100%", height: 100})
.size({ width: "100%", height: 100 })
.backgroundColor(0xd2cab3)
.clip(true)
// Grid child component width/height = 3/2
Text('using container: grid').fontSize(14).fontColor(0xCCCCCC).width('100%')
Grid() {
ForEach(this.children, (item) => {
......@@ -54,12 +57,12 @@ struct AspectRatioExample {
.fontSize(40)
.aspectRatio(1.5)
}
}, item=>item)
}, item => item)
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.size({width: "100%", height: 165})
.size({ width: "100%", height: 165 })
.backgroundColor(0xd2cab3)
}.padding(10)
}
......@@ -67,47 +70,53 @@ struct AspectRatioExample {
```
**Figure 1** Portrait display
![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif)
**Figure 2** Landscape display
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif)
```ts
class ContainerInfo {
label : string = ''
size : string = ''
label: string = '';
size: string = '';
}
class ChildInfo {
text : string = ''
priority : number = 0
text: string = '';
priority: number = 0;
}
@Entry
@Component
struct DisplayPriorityExample {
private container : ContainerInfo[] = [
{label: 'Big container', size: '90%'},
{label: 'Middle container', size: '50%'},
{label: 'Small container', size: '30%'}
// Display the container size.
private container: ContainerInfo[] = [
{ label: 'Big container', size: '90%' },
{ label: 'Middle container', size: '50%' },
{ label: 'Small container', size: '30%' }
]
private children : ChildInfo[] = [
{text: '1\n(priority:2)', priority: 2},
{text: '2\n(priority:1)', priority: 1},
{text: '3\n(priority:3)', priority: 3},
{text: '4\n(priority:1)', priority: 1},
{text: '5\n(priority:2)', priority: 2}
private children: ChildInfo[] = [
{ text: '1\n(priority:2)', priority: 2 },
{ text: '2\n(priority:1)', priority: 1 },
{ text: '3\n(priority:3)', priority: 3 },
{ text: '4\n(priority:1)', priority: 1 },
{ text: '5\n(priority:2)', priority: 2 }
]
@State currentIndex : number = 0
@State currentIndex: number = 0;
build() {
Column({space: 10}) {
Column({ space: 10 }) {
// Switch the size of the parent container.
Button(this.container[this.currentIndex].label).backgroundColor(0x317aff)
.onClick((event: ClickEvent) => {
this.currentIndex = (this.currentIndex + 1) % this.container.length
.onClick(() => {
this.currentIndex = (this.currentIndex + 1) % this.container.length;
})
Flex({justifyContent: FlexAlign.SpaceBetween}) {
ForEach(this.children, (item)=>{
// Set the width for the parent flex container through variables.
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
ForEach(this.children, (item) => {
// Bind the display priority to the child component through displayPriority.
Text(item.text)
.width(120)
.height(60)
......@@ -115,11 +124,11 @@ struct DisplayPriorityExample {
.textAlign(TextAlign.Center)
.backgroundColor(0xbbb2cb)
.displayPriority(item.priority)
}, item=>item.text)
}, item => item.text)
}
.width(this.container[this.currentIndex].size)
.backgroundColor(0xd2cab3)
}.width("100%").margin({top:50})
}.width("100%").margin({ top: 50 })
}
}
......
# Location
The location attribute sets the alignment mode, layout direction, and position of a component.
The location attributes set the alignment mode, layout direction, and position of a component.
> **NOTE**
>
......@@ -12,25 +12,25 @@ The location attribute sets the alignment mode, layout direction, and position o
| Name| Type| Description|
| -------- | -------- | -------- |
| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment of the component content. This attribute is valid only when the values of **width** and **height** are greater than the size of the component content.<br>Default value: **Alignment.Center**|
| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.<br>Default value: **Alignment.Center**|
| direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.<br>Default value: **Direction.Auto**|
| position | [Position](ts-types.md#position8) | Offset of the component anchor point relative to the top start edge of the parent component. The offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.|
| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.<br>Default value:<br>**{<br>x: 0,<br>y: 1**<br>} |
| offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>Default value:<br>**{<br>x: 0,<br>y: 1<br>}** |
| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.|
| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} |
| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} |
| alignRules<sup>9+</sup> | {<br>left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }<br>} | Alignment rules relative to the container.<br>- **left**: left-aligned.<br>- **right**: right-aligned.<br>- **middle**: center-aligned.<br>- **top**: top-aligned.<br>- **bottom**: bottom-aligned.<br>- **center**: center-aligned.<br>**NOTE**<br>- **anchor**: ID of the component that functions as the anchor point.<br>- **align**: alignment mode relative to the anchor component.|
## Example
### Example 1
```ts
// xxx.ets
@Entry
@Component
struct PositionExample {
struct PositionExample1 {
build() {
Column() {
Column({space: 10}) {
Column({ space: 10 }) {
// When the component content is within the area specified by the component width and height, set the alignment mode of the content in the component.
Text('align').fontSize(9).fontColor(0xCCCCCC).width('90%')
Text('top start')
.align(Alignment.TopStart)
......@@ -39,6 +39,14 @@ struct PositionExample {
.fontSize(16)
.backgroundColor(0xFFE4C4)
Text('Bottom end')
.align(Alignment.BottomEnd)
.height(50)
.width('90%')
.fontSize(16)
.backgroundColor(0xFFE4C4)
// To arrange the child components from left to right, set direction of the parent container to Direction.Auto or Direction.Ltr, or leave it to the default value.
Text('direction').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row() {
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
......@@ -47,6 +55,15 @@ struct PositionExample {
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
}
.width('90%')
.direction(Direction.Auto)
// To arrange the child components from right to left, set direction of the parent container to Direction.Rtl.
Row() {
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
Text('2').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
Text('3').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
}
.width('90%')
.direction(Direction.Rtl)
}
}
......@@ -55,54 +72,75 @@ struct PositionExample {
}
```
![en-us_image_0000001212218456](figures/en-us_image_0000001212218456.gif)
![align.png](figures/align.png)
### Example 2
```ts
// xxx.ets
@Entry
@Component
struct PositionExample2 {
build() {
Column({ space: 20 }) {
// Set the offset of the component's upper left corner relative to the parent component's upper left corner.
Text('position').fontSize(12).fontColor(0xCCCCCC).width('90%')
Row({ space: 20 }) {
Text('1').size({ width: '45%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }) .fontSize(16)
Text('2 position(25, 15)')
.size({ width: '60%', height: '30' }).backgroundColor(0xbbb2cb).border({ width: 1 })
.fontSize(16).align(Alignment.Start)
.position({ x: 25, y: 15 })
Row() {
Text('1').size({ width: '30%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
Text('2 position(30, 10)')
.size({ width: '60%', height: '30' })
.backgroundColor(0xbbb2cb)
.border({ width: 1 })
.fontSize(16)
.align(Alignment.Start)
.position({ x: 30, y: 10 })
Text('3').size({ width: '45%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
Text('4 position(50%, 70%)')
.size({ width: '50%', height: '50' }).backgroundColor(0xbbb2cb).border({ width: 1 }).fontSize(16)
.size({ width: '50%', height: '50' })
.backgroundColor(0xbbb2cb)
.border({ width: 1 })
.fontSize(16)
.position({ x: '50%', y: '70%' })
}.width('90%').height(100).border({ width: 1, style: BorderStyle.Dashed })
// Offset relative to the start point. x indicates the horizontal distance between the end point and the start point. If the value of x is greater than 0, the component is offset to the left. Otherwise, the component is offset to the right.
// y indicates the vertical distance between the end point and the start point. If the value of y is greater than 0, the component is offset to the top. Otherwise, the component is offset to the bottom.
Text('markAnchor').fontSize(12).fontColor(0xCCCCCC).width('90%')
Stack({ alignContent: Alignment.TopStart }) {
Row()
.size({ width: '100', height: '100' })
.backgroundColor(0xdeb887)
Image($r('app.media.ic_health_heart'))
Text('text')
.size({ width: 25, height: 25 })
.backgroundColor(Color.Green)
.markAnchor({ x: 25, y: 25 })
Image($r('app.media.ic_health_heart'))
Text('text')
.size({ width: 25, height: 25 })
.markAnchor({ x: 25, y: 25 })
.position({ x: '100%', y: '100%' })
.backgroundColor(Color.Green)
.markAnchor({ x: -100, y: -25 })
Text('text')
.size({ width: 25, height: 25 })
.backgroundColor(Color.Green)
.markAnchor({ x: 25, y: -25 })
}.margin({ top: 25 }).border({ width: 1, style: BorderStyle.Dashed })
// Offset of the component relative to itself. If the value of x is greater than 0, the component is offset to the right. Otherwise, the component is offset to the left. If the value of y is greater than 0, the component is offset to the bottom. Otherwise, the component is offset to the top.
Text('offset').fontSize(12).fontColor(0xCCCCCC).width('90%')
Row() {
Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
Text('2\noffset(15, 15)')
.size({ width: 120, height: '50' }).backgroundColor(0xbbb2cb).border({ width: 1 })
.fontSize(16).align(Alignment.Start)
.offset({ x: 15, y: 15 })
Text('2 offset(15, 30)')
.size({ width: 120, height: '50' })
.backgroundColor(0xbbb2cb)
.border({ width: 1 })
.fontSize(16)
.align(Alignment.Start)
.offset({ x: 15, y: 30 })
Text('3').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16)
Text('4\noffset(-10%, 20%)')
.size({ width: 150, height: '50' }) .backgroundColor(0xbbb2cb).border({ width: 1 }).fontSize(16)
.offset({ x: '-10%', y: '20%' })
Text('4 offset(-10%, 20%)')
.size({ width: 100, height: '50' })
.backgroundColor(0xbbb2cb)
.border({ width: 1 })
.fontSize(16)
.offset({ x: '-5%', y: '20%' })
}.width('90%').height(100).border({ width: 1, style: BorderStyle.Dashed })
}
.width('100%').margin({ top: 25 })
......@@ -110,4 +148,4 @@ struct PositionExample2 {
}
```
![en-us_image_0000001256858409](figures/en-us_image_0000001256858409.gif)
![position.png](figures/position.png)
......@@ -8,10 +8,9 @@ You can set overlay text for a component.
## Attributes
| Name | Type | Description |
| ------- | ----------------------------- | ------------------------- |
| overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {<br> x?: number,<br> y?: number<br> }<br>} | Overlay added to the component. The overlay has the same layout as the component.<br>Default value:<br>{<br>align: Alignment.Center,<br>offset: {0, 0}<br>} |
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {x?: number, y?: number}<br>} | {<br>align: Alignment.Center,<br>offset: {0, 0}<br>} | Overlay added to the component.<br> **value**: mask text.<br>**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.<br>If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.|
## Example
......@@ -28,7 +27,10 @@ struct OverlayExample {
Column() {
Image($r('app.media.img'))
.width(240).height(240)
.overlay("Winter is a beautiful season, especially when it snows.", { align: Alignment.Bottom, offset: { x: 0, y: -15 } })
.overlay("Winter is a beautiful season, especially when it snows.", {
align: Alignment.Bottom,
offset: { x: 0, y: -15 }
})
}.border({ color: Color.Black, width: 2 })
}.width('100%')
}.padding({ top: 20 })
......
# Size
The size attributes are used to set the width, height, padding, and margin of a component.
The size attributes set the width, height, and margin of a component.
> **NOTE**
>
......@@ -16,9 +16,9 @@ The size attributes are used to set the width, height, padding, and margin of a
| height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn. |
| size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component. |
| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.<br>Default value: **0**<br>When **padding** is set to a percentage, the width of the parent container is used as the basic value.|
| margin | [Margin](ts-types.md#margin)) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.|
| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.|
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} |
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>Default value: **0**|
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.|
## Example
......@@ -31,30 +31,41 @@ struct SizeExample {
build() {
Column({ space: 10 }) {
Text('margin and padding:').fontSize(12).fontColor(0xCCCCCC).width('90%')
// The width is 80, the height is 80, the padding is 20, and the margin is 20.
Row() {
// Width: 80; height: 80; margin: 20 (blue area); padding: 10 (white area)
Row() {
Row().size({ width: '100%', height: '100%' }).backgroundColor(0xAFEEEE)
}.width(80).height(80).padding(20).margin(20).backgroundColor(0xFDF5E6)
}.backgroundColor(0xFFA500)
Row().size({ width: '100%', height: '100%' }).backgroundColor(Color.Yellow)
}
.width(80)
.height(80)
.padding(10)
.margin(20)
.backgroundColor(Color.White)
}.backgroundColor(Color.Blue)
Text('constraintSize').fontSize(12).fontColor(0xCCCCCC).width('90%')
Text('this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text')
.width('90%')
.constraintSize({ maxWidth: 200 })
Text('layoutWeight').fontSize(12).fontColor(0xCCCCCC).width('90%')
// When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.
// When the container size is determined, the component occupies the space along the main axis based on the layout weight, and the component size setting is ignored.
Row() {
// Weight 1
// Weight 1: The component occupies 1/3 of the remaining space along the main axis.
Text('layoutWeight(1)')
.size({ width: '30%', height: 110 }).backgroundColor(0xFFEFD5).textAlign(TextAlign.Center)
.layoutWeight(1)
// Weight 2
// Weight 2: The component occupies 2/3 of the remaining space along the main axis.
Text('layoutWeight(2)')
.size({ width: '30%', height: 110 }).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.layoutWeight(2)
// The default weight is 0.
// If layoutWeight is not set, the component is rendered based on its own size setting.
Text('no layoutWeight')
.size({ width: '30%', height: 110 }).backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
}.size({ width: '90%', height: 140 }).backgroundColor(0xAFEEEE)
}.width('100%').margin({ top: 5 })
}}
}
}
```
![en-us_image_0000001257138367](figures/en-us_image_0000001257138367.gif)
![size](figures/size.png)
# Text Style
The text style attributes are used to set the style for text in a component.
The text style attributes set the style for text in a component.
> **NOTE**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes
| Name | Type | Description |
| -----------| ---------------------------------------- | ------------------------------------ |
| fontColor | [ResourceColor](ts-types.md#resourcecolor) | Font color. |
| fontSize | Length \| [Resource](ts-types.md#resource) | Font size. If the value is of the number type, the unit fp is used. |
| fontSize | [Length](ts-types.md#length) | Font size. If the value is of the number type, the unit fp is used. The default font size is 10. This attribute cannot be set in percentage. |
| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.<br>Default value: **FontStyle.Normal** |
| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.<br>Default value: **FontWeight.Normal** |
| fontFamily | string \| [Resource](ts-types.md#resource) | Font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.|
| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in FontWeight.<br>Default value: **FontWeight.Normal** |
| fontFamily | string \| [Resource](ts-types.md#resource) | Font family.<br>Default value: **'HarmonyOS Sans'**<br>Currently, only the default font is supported. |
## Example
......@@ -30,40 +30,38 @@ struct TextStyleExample {
build() {
Column({ space: 5 }) {
Text('default text')
Text('text font color red')
.fontColor(Color.Red)
Text('text font size 20')
.fontSize(20)
Text('text font style Italic')
.fontStyle(FontStyle.Italic)
Text('text fontWeight bold')
.fontWeight(700)
Text('text fontFamily sans-serif')
.fontFamily('sans-serif')
Text('red 20 Italic bold cursive text')
Divider()
Text('text font color red').fontColor(Color.Red)
Divider()
Text('text font default')
Text('text font size 10').fontSize(10)
Text('text font size 10fp').fontSize('10fp')
Text('text font size 20').fontSize(20)
Divider()
Text('text font style Italic').fontStyle(FontStyle.Italic)
Divider()
Text('text fontWeight bold').fontWeight(700)
Text('text fontWeight lighter').fontWeight(FontWeight.Lighter)
Divider()
Text('red 20 Italic bold text')
.fontColor(Color.Red)
.fontSize(20)
.fontStyle(FontStyle.Italic)
.fontWeight(700)
.fontFamily('cursive')
.textAlign(TextAlign.Center)
.width('90%')
Text('Orange 18 Normal source-sans-pro text')
.fontWeight(FontWeight.Bold)
Divider()
Text('Orange 18 Normal text')
.fontColor(Color.Orange)
.fontSize(18)
.fontStyle(FontStyle.Normal)
.fontWeight(400)
.fontFamily('source-sans-pro,cursive,sans-serif')
}.width('100%')
}
}
```
![en-us_image_0000001256978333](figures/en-us_image_0000001256978333.png)
![textstyle](figures/textstyle.png)
......@@ -10,7 +10,7 @@ The visibility attribute controls whether a component is visible.
| Name | Type | Description |
| ---------- | ---------------------------- | ------------------------------------------ |
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is hidden, it needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../ui/ts-rending-control-syntax-if-else.md) instead under scenarios where consistently high performance is required.<br>Default value: **Visibility.Visible**|
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is invisible, it still needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../quick-start/arkts-rendering-control.md#conditional-rendering) instead under scenarios where consistently high performance is required.<br>Default value: **Visibility.Visible**|
## Example
......@@ -23,20 +23,21 @@ struct VisibilityExample {
build() {
Column() {
Column() {
Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE)
Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC)
// The component is hidden, and no placeholder is used.
Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.None).width('90%').height(80).backgroundColor(0xAFEEEE)
Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC)
// The component is hidden, and a placeholder is used for it in the layout.
Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Hidden).width('90%').height(80).backgroundColor(0xAFEEEE)
// The component is visiable, which is the default display mode.
Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE)
}.width('90%').border({ width: 1 })
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001257058421](figures/en-us_image_0000001257058421.gif)
![visibility.png](figures/visibility.png)
......@@ -25,20 +25,24 @@ struct ZIndexExample {
build() {
Column() {
Stack() {
// Components are stacked. By default, the component defined later is on the top.
Text('first child, zIndex(2)')
.size({width: '40%', height: '30%'}).backgroundColor(0xbbb2cb)
// Components are stacked. By default, the component defined later is on the top. A component with a larger zIndex value is displayed before one with a smaller zIndex value.
Text('1, zIndex(2)')
.size({ width: '40%', height: '30%' }).backgroundColor(0xbbb2cb)
.zIndex(2)
// The default value is 0.
Text('second child, default zIndex(0)')
.size({width: '90%', height: '80%'}).backgroundColor(0xd2cab3).align(Alignment.TopStart)
Text('third child, zIndex(1)')
.size({width: '70%', height: '50%'}).backgroundColor(0xc1cbac).align(Alignment.TopStart)
Text('2, default zIndex(1)')
.size({ width: '70%', height: '50%' }).backgroundColor(0xd2cab3).align(Alignment.TopStart)
.zIndex(1)
Text('3, zIndex(0)')
.size({ width: '90%', height: '80%' }).backgroundColor(0xc1cbac).align(Alignment.TopStart)
}.width('100%').height(200)
}.width('100%').height(200)
}
}
```
Display of child components in the **\<Stack>** component when **zIndex** is not set
![en-us_image_0000001257058443](figures/en-us_image_0000001257058443.png)
![nozindex.png](figures/nozindex.png)
Display of child components in the **\<Stack>** component when **zIndex** is set
![zindex.png](figures/zindex.png)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册