中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
Tips:
@Preview @Component export default struct TitleContainer { build() { // 行布局 Row() { } } }
二、组件布局 使用Row容器进行行布局,从左到右分别是:返回按钮(图片)、标题内容(文本)、确定按钮(图片)。在images目录下添加按钮图片,图片文件见文章最后的附件。
build() { // 行布局 Row() { // 返回按钮 Button() { Image('images/icon_back.png') .objectFit(ImageFit.Fill); } .width(24) .height(24) .backgroundColor("#00000000") .onClick(() => { //TODO 按钮事件 }); // 标题内容 Text('标题') .fontSize(20) .lineHeight(28) .fontColor('#182431') .fontWeight(FontWeight.Bold) .margin({ left: 16 }); // 占位 Blank(); } .width("100%") .height(56) .padding({ left: 24, right: 24 }); }
效果如下: 三、组件属性 为了更灵活方便页面使用该组件时,可自定义返回按钮的图片、标题内容和点击返回按钮时触发的事件,我们需要给组件定义对应的三个属性,使用组件时给组件传参数值。
// 返回按钮图片 private backImg: string | Resource = $r("app.media.icon_cancel"); // 返回按钮点击事件 private backFunc?: () => void; // 标题 private title: string | Resource = "标题";
四、代码优化
build() { // 行布局 Row() { // 返回按钮 Button() { Image(this.backImg == null ? $r("app.media.icon_back") : this.backImg) .objectFit(ImageFit.Fill); } .width(SizeUtil.getVp($r("app.float.title_button_size"))) .height(SizeUtil.getVp($r("app.float.title_button_size"))) .backgroundColor("#00000000") .onClick(() => { this.backFunc ? this.backFunc : router.back(); }); // 标题内容 Text(this.title) .fontSize(SizeUtil.getFp($r("app.float.title_font_size"))) .lineHeight(SizeUtil.getVp($r("app.float.title_line_height"))) .fontColor($r("app.color.grey_divider")) .fontWeight(FontWeight.Bold) .margin({ left: SizeUtil.getVp($r("app.float.title_margin")) }); // 占位 Blank(); if (this.closeHandle) { this.closeHandle(); } } .width("100%") .height(SizeUtil.getVp($r("app.float.title_height"))) .padding({ left: SizeUtil.getVp($r("app.float.title_horizon_margin")), right: SizeUtil.getVp($r("app.float.title_horizon_margin")) }); }
float.json文件
{ "name": "title_button_size", "value": "24" }, { "name": "title_font_size", "value": "20" }, { "name": "title_line_height", "value": "28" }, { "name": "title_margin", "value": "16" }, { "name": "title_height", "value": "56" }, { "name": "title_horizon_margin", "value": "24" }
color.json文件
{ "name": "grey_divider", "value": "#182431" }
图片请见关联的资源可下载。
微信扫码分享