SwiftUI:如何计算文本视图的宽度



我需要计算未知数量的文本视图(与睡眠中的时间一样多(。每个文本视图只是一个小时,例如文本("12"(、文本("1"(等

我需要知道所有组合的小时文本视图的宽度,这样我就可以从整体几何图形中减去相应的空间。下面是一个widthOfString函数,它可能与UIKit一起使用,但似乎无法在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())

My Helper功能和扩展:

//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
}
}

不是问题的直接答案,但可能需要研究的方向是PreferenceKey协议与GeometryReader的结合。例如,下面的代码在背景中绘制一个RoundedRectangle,它修改了视图的高度:

struct HeightPreferenceKey: PreferenceKey {
static var defaultValue: [CGFloat] = []

static func reduce(value: inout [CGFloat], nextValue: () -> [CGFloat]) {
value.append(contentsOf: nextValue())

}

typealias Value = [CGFloat]
}
struct HeightPreferenceViewSetter: View {
var body: some View {
GeometryReader { geometry in
RoundedRectangle(cornerRadius: 13)
.fill(Color.gray)
.preference(key: HeightPreferenceKey.self,
value: [geometry.size.height]) 
}
}
}
struct HeightModifier: ViewModifier {
func body(content: Content) -> some View {
content
.background(HeightPreferenceViewSetter())

}
}

相关内容

  • 没有找到相关文章

最新更新