实现的效果如图
自定义组件代码:
go
package widget
import (
"fmt"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
"strconv"
"time"
)
var timeLayout = "15:04"
type SelectTime struct {
Container *fyne.Container
}
func NewSelectTime(startTime time.Time, endTime time.Time, fun func(t *time.Time, t2 *time.Time)) *SelectTime {
picker := &SelectTime{}
// 创建分隔符标签
// 创建小时、分钟、秒的选择框
startHourW := widget.NewSelectEntry(generateOptions(0, 23))
startHourW.Text = strconv.Itoa(startTime.Hour())
startMinuteW := widget.NewSelectEntry(generateOptions(0, 59))
startMinuteW.Text = strconv.Itoa(startTime.Minute())
endHourW := widget.NewSelectEntry(generateOptions(0, 23))
endHourW.Text = strconv.Itoa(endTime.Hour())
endMinuteW := widget.NewSelectEntry(generateOptions(0, 59))
endMinuteW.Text = strconv.Itoa(endTime.Minute())
var onChangeUpdate = func(s string) {
startTime, _ := time.Parse(timeLayout, startHourW.Text+":"+startMinuteW.Text)
endTime, _ := time.Parse(timeLayout, endHourW.Text+":"+endMinuteW.Text)
fun(&startTime, &endTime)
}
startHourW.OnChanged = onChangeUpdate
startMinuteW.OnChanged = onChangeUpdate
endHourW.OnChanged = onChangeUpdate
endMinuteW.OnChanged = onChangeUpdate
// 创建时间选择器容器
picker.Container = container.NewHBox(
startHourW,
widget.NewLabel(":"),
startMinuteW,
widget.NewSeparator(),
endHourW,
widget.NewLabel(":"),
endMinuteW,
)
return picker
}
// generateOptions 生成从 start 到 end 的数字选项
func generateOptions(start, end int) []string {
options := make([]string, end-start+1)
for i := start; i <= end; i++ {
options[i-start] = fmt.Sprintf("%02d", i)
}
return options
}
使用时候,引用代码:
go
selectTime := widget2.NewSelectTime(time.Now(), time.Now(), func(t *time.Time, t2 *time.Time) {
updateTimeStr := t.Format("15:04") + "-" + t2.Format("15:04")
log.Println("现在时间是", updateTimeStr)
_ = externalString.Set(updateTimeStr)
})