I am porting and old Objective C application where I used attributed string to write text in - (void)drawRect:(CGRect)rect.
I am not able to draw text using the SwiftUI Path though. I found a similar question without any answer (Mac OS X - SwiftUI - how to draw a String (text) together with some path )
Let suppose that I need to write a label over an horizontal line in the middle of the screen.
Using the following code, the line shows up in the expected position. Text doesn't show up, instead.
struct TestView: View {
var body: some View {
GeometryReader { geometry in
contentView(geometry: geometry)
}
}
func contentView(geometry: GeometryProxy) -> some View {
let content = VStack {
ZStack {
LineAndText()
.stroke()
}
}
return content
}
}
struct LineAndText: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 0, y: rect.size.height / 2))
path.addLine(to: CGPoint(x: rect.width, y: rect.size.height / 2))
let label = "label"
label.draw(at: CGPoint(x:0, y:rect.size.height / 2))
}
}
}
How do I write text in the desired position?
NOTE: The real scenario is much more complex, I have many lines with different vertical and horizontal labels so I need to control the label position at pixel level.