简体   繁体   English

SwiftUI:文本在屏幕上的绝对定位

[英]SwiftUI: Absolute positioning of text on screen

Am updating a compass view from UIKit to SwiftUI. The original looks like this:我正在将指南针视图从 UIKit 更新为 SwiftUI。原件如下所示:

在此处输入图像描述

But haven't worked out how to display the text, currently nothing:但是还没有弄清楚如何显示文本,目前没有:

在此处输入图像描述

This is the code that I am using:这是我正在使用的代码:

struct DisplayDirections: Shape {

    func path(in rect: CGRect) -> Path {

        var path = Path()

        let outerRadius = 134.0

        var farX = 0.0

        var farY = 0.0

        let offset = 16.0

        var degree = 0.0

        var radians = 0.0

        for result in ["S", "SW", "W", "NW", "N", "NE", "E", "SE"] {

            radians = (CGFloat(degree) * .pi / 180.0)

            farX = outerRadius + cos(radians) * CGFloat(outerRadius) + offset

            farY = outerRadius + sin(radians) * CGFloat(outerRadius) + offset

            Text(result)

                .font(.title)

                .foregroundColor(.black)

                .background(.red)

                .position(x: farX, y: farY)

                .rotationEffect(.degrees(degree))

                .fixedSize()

            degree = degree + 45.0

            print(result) // Just to get some output so I know the loop is working

        }

        return path

    }

}

What am I doing wrong?我究竟做错了什么?

Working, all thanks to Lorem Ipsum's hints.工作,都归功于 Lorem Ipsum 的提示。 This code has to live in the main Stack and can't be called from Structs like the rest of the lines and circles that make up the clock face.此代码必须存在于主堆栈中,不能从构成钟面的线条和圆圈的 rest 之类的结构中调用。 The NSEW literals are put on with a similar construct to the degrees part which are listed below. NSEW 文字采用与下面列出的度数部分类似的结构。

斯威夫特用户界面版本

// Draw Degrees

ForEach(Array(stride(from: 0, to: 360, by: 10)), id: \.self) { index in
    let degree: Double = Double.pi * 2 / Double(360)
    let itemDegree = degree * Double(index)
    VStack {
        Text(String(index))
        .font(.system(size: 8))
        .foregroundColor(.black)
        Spacer()
    }
    .rotationEffect(.radians(itemDegree))
}
.frame(width: 288, height: 288)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM