鸿蒙HarmonyOS开发生日选择弹框
生日选择弹框和城市选择弹框差不多,都是通过观察上一个数据变化来设置自己的数据
一、思路:
一个弹框上建三个compoent,一个年,一个月,一个日。日的数据是根据年和月进行变化的
二、效果图:
三、视频效果:
鸿蒙Next开发教程实战案例源码分享-生日选择弹框
四、关键源码如下:
// 联系:893151960
@Component
export struct FirstLevelComponent {@State labelList: string[] = [];@Consume selectFirstIndex: number;@Consume currentFirst: string;@Consume dataSource: string[];aboutToAppear() {for (let i = 0; i < this.dataSource.length; i++) {this.labelList.push(this.dataSource[i])if (this.dataSource[i] === this.currentFirst) {this.selectFirstIndex = i;}}this.currentFirst = this.dataSource[this.selectFirstIndex]}build() {Column() {Column() {if (this.labelList.length === 0) {Text('暂无数据').fontSize(20)} else {TextPicker({ range: this.labelList, selected: this.selectFirstIndex }).onChange((value: string|string[], index: number|number[]) => {if (typeof index === 'number') {this.selectFirstIndex = indexthis.currentFirst = this.dataSource[index]}}).selectedTextStyle({color:$r('app.color.color_main')}).canLoop(false)}}.backgroundColor(Color.White).border({ color: '#e2e2e2', width: { right: 0.5 }}).width('100%').layoutWeight(1).justifyContent(FlexAlign.Center)}.height('100%')}
}
/*** @author :congge* @date : 2024-01-24 11:45* @desc : 生日选择专用弹框**/
@CustomDialog
export default struct BirthdayPickerDialog {@Provide currentFirst: string = '';@Provide currentSecond: string = '';@Provide currentThree: string = '';@Provide selectFirstIndex: number = 0;//注意; 这位置很可能和数组的位置对不上的,因为它的起点是以为左边选中开始的@Provide selectSecondIndex: number = 0;controller: CustomDialogControllertitle: string = '选择生日' //弹窗的提示文本@Provide dataSource: string[] = CommonConstants.YEAR@Provide secondOnlyDataSource: string[] = CommonConstants.MONTHresultCallback?:(arg0:string,arg1:string,arg2:string) => voidaboutToAppear() {this.currentFirst = this.dataSource[0];this.currentSecond = this.secondOnlyDataSource[0];}build() {Column() {Text(this.title).fontSize(20).textAlign(TextAlign.Center).margin({ top: 10, bottom: 10 });Row() {FirstLevelComponent().width('33%');// 手动给线Divider().vertical(true).color($r('app.color.color_e2')).width(0.5)SecondOnlyLevelComponent().width('33%');Divider().vertical(true).color($r('app.color.color_e2')).width(0.5)DayLevelComponent().width('33%');}.height('40%')Flex({ justifyContent: FlexAlign.SpaceAround, alignItems: ItemAlign.Center }) {Button($r('app.string.cancel'), { type: ButtonType.Normal }).onClick(() => {this.controller?.close()}).backgroundColor(0xffffff).fontColor(Color.Black).layoutWeight(1).height('100%')Divider().vertical(true).strokeWidth(1).color('#F1F3F5').opacity(1).height('100%')Button($r('app.string.sure'), { type: ButtonType.Normal }).onClick(() => {this.controller?.close()this.resultCallback?.(this.currentFirst,this.currentSecond,this.currentThree)}).backgroundColor(0xffffff).fontColor($r('app.color.color_main')).layoutWeight(1).height('100%')}.height(50)}}
}
五、完整项目demo结构图:
有需要完整源码demo可私信我