首页 > 解决方案 > 显示 int 数组列表的优雅方式

问题描述

大家好,我正在与LazyVGrid我的SwiftUI项目合作以显示时间列表...

这是小时数

let hoursList = [09, 10, 10, 11, 11, 12, 12, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18]
    
let columns = Array(repeating: GridItem(), count: 4)
LazyVGrid(columns: columns, alignment: .center, spacing: 10) {
    ForEach(viewModel.hoursList) { hours in
        Text("\(hours)")
    }
    ///////////
    // more elegant way to get the times as in the array?
    //////////
}

正如您在数组中看到的那样,有重复的时间,例如10 - 10、11 - 11

有没有一种更优雅的方法来获取像上面那样的数组但不指定每个数字?我可以使用更优雅的方式而不是直接使用 ' hourList' 来达到我的目标吗?

标签: iosswiftiphoneswiftui

解决方案


小时和分钟应转换为数字系统,因此
HHmm从时钟将是 ( HH).( mm/60) in Numeral

02:00 是 2.0
06:30 是 6.5
08:45 是 8.75
15:55 是 15.916666...

extension Double {
    var minute: Int { Int(self * 60) - Int(self)*60 }
}

let hoursList = [9.5, 10.0, 10.5, 12, 12.5, 14.5, 15, 16, 17, 17.75, 18, 18.25]

let columns = Array(repeating: GridItem(), count: 4)
LazyVGrid(columns: columns, alignment: .center, spacing: 10) {
    ForEach(viewModel.hoursList) { hour in
        Text(String(format: "%d : %.2d", Int(hour), hour.minute))
    }
}

推荐阅读