4 UI 组件-Text 组件
文本组件是用于显示一段文本的基础组件,同时支持丰富的样式和布局配置,还可以包含 Span、ImageSpan 等子组件。
4.1 文本组件的定义与属性
接口:
Text(content?: string | Resource, options?: TextOptions)
属性说明:
- content:显示的文本内容。
- 样式设置:可以通过 .style() 方法为文本指定对齐方式、字体大小、边框、填充等样式。
4.2 使用示例
content:要显示的文本内容,一个简单的例子如下:
// xxx.ets
@Extend(Text)
function style(TextAlign: TextAlign) {
.textAlign(TextAlign)
.fontSize(12)
.border({ width: 1 })
.padding(10)
.width('100%')
}
@Entry
@Component
struct TextExample1 {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
// 文本水平方向对齐方式设置
// 单行文本
Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
Text('TextAlign set to Center.')
.style(TextAlign.Center)
Text('TextAlign set to Start.')
.style(TextAlign.Start)
Text('TextAlign set to End.')
.style(TextAlign.End)
// 多行文本
Text('This is the text content with textAlign set to Center.')
.style(TextAlign.Center)
Text('This is the text content with textAlign set to Start.')
.style(TextAlign.Start)
Text('This is the text content with textAlign set to End.')
.style(TextAlign.End)
// 文本超长时显示方式
Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
// 超出maxLines截断内容展示
Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.')
.textOverflow({ overflow: TextOverflow.Clip })
.maxLines(1)
.style(TextAlign.Start)
// 超出maxLines展示省略号
Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(1)
.style(TextAlign.Start)
Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
Text('This is the text with the line height set. This is the text with the line height set.')
.style(TextAlign.Start)
Text('This is the text with the line height set. This is the text with the line height set.')
.style(TextAlign.Start)
.lineHeight(20)
}.height(600).width(340).padding({ left: 35, right: 35, top: 35 })
}
}