1

説明する必要があるテキスト ビューの数が不明です (睡眠中に経過する時間数)。各 Text ビューは、Text("12")、Text("1") などの 1 時間だけです。

全体のジオメトリからそれに応じてスペースを差し引くことができるように、結合されたすべての時間テキスト ビューの幅を知る必要があります。以下は、widthOfStringUIKit で動作した可能性がある関数ですが、SwiftUI で適切なサイズを計算していないようです。どうすればこれを達成できますか?

使用例:

  Spacer()
    .frame(width: CGFloat(hourAsDate.timeIntervalSince(hoursBetweenSleepStartAndEnd[(hoursBetweenSleepStartAndEnd.firstIndex(of: hourAsDate) ?? 0) - 1]) / totalSleepSeconds)  * calculateSpaceOfHourText())
  Text("\(calendar.component(.hour, from: hourAsDate))")
    .font(Font.system(size: 13.0))
  Spacer()
    .frame(width: CGFloat(sleepEndDate.timeIntervalSince(hourAsDate) / totalSleepSeconds)  * calculateSpaceOfHourText())

私のヘルパー関数と拡張機能:

       //helper
    private func calculateSpaceOfHourText() -> CGFloat {
    
    //The idea here is to try to add up all the space that is taken up by hour Text views and subtract it from the total with of geometry
    
        var hoursToUseForCalculationOfSpace = hoursBetweenSleepStartAndEnd
        
        if hoursBetweenSleepStartAndEnd.first ?? Date() <= sleepStartDate {
            hoursToUseForCalculationOfSpace.removeFirst()
        }
        
        if hoursBetweenSleepStartAndEnd.last ?? Date() >= sleepEndDate {
            hoursToUseForCalculationOfSpace.removeLast()
        }
        return (proxy.size.width - hoursToUseForCalculationOfSpace.map { calendar.component(.hour, from: $0) }.map { "\($0)".widthOfString(usingFont: UIFont.systemFont(ofSize: 13, weight: .regular)) }.reduce(0, +))
    }
}

extension String {
   func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        //print("THIS width = \(size.width)")
        return size.width
    }
}
4

1 に答える 1