SwiftUI 中 Text 组建的文本显示

81 阅读1分钟

image.png 我打算做一个刷题的应用,想要在应用中复原 pdf 的效果,但是同样是 Courier 字体,左侧是 PDF 中的,字体比较细,在 ipad 中字体比较粗,哪怕我设置了字体是extraLight字体仍然很细

import SwiftUI

  


struct ContentView: View {

    var body: **some** View {

        ScrollView {

            VStack(alignment: .leading) {

                

                Text("4. Consider the following method.")

                    .font(.custom("Times-Roman", size: 24))

                CodeBlock()

                Text("What is printed as a result of the call `message(5, 15, 5)`")

                    .font(.custom("Times-Roman", size: 24))

                // 行内正则渲染格式的定制化,

                Text(

                """

            (A) XY

            """).font(.custom("Times-Roman", size: 24).monospaced()).padding()

                            Text(

                            """

            (B) XYZ

            """).font(.custom("Times-Roman", size: 24)).padding()

                            Text(

                            """

            (C) Y

            """).font(.custom("Times-Roman", size: 24)).padding()

                            Text(

                            """

            (D) YY

            """).font(.custom("Times-Roman", size: 24)).padding()

                            Text(

                            """

            (E) Z

            """).font(.custom("Times-Roman", size: 24)).padding()

                

            CodeBlock()

                

                

            }

        }

    }

}

  


// 可以遇到 ``` 的代码,我自己渲染指定的格式就好了

// 官方给出了 swift markdown syntax 的渲染

  


**struct** CodeBlock: View {

    **var** body: **some** View {

        Text("""

public static void message(int a, int b)

{

    if (a < 10)

    {

        if (b < 10)

        {

            System.out.print("X");

        }

        System.out.print("Y");

    }

    if (c < 10)

    {

        if (b > 10)

        {

            System.out.print("Y");

        }

        else

        {

            System.out.print("Z");

        }

    }

}

""")

        .font(.custom("Courier", size: 24, relativeTo: .body).weight(.ultraLight).monospaced())

            .padding([.top, .bottom], 5)

            .padding([.leading], 40)

    }

}

掘金从 xcode 粘贴代码似乎有点问题,一些系统关键字会添加星号,然后会添加额外的恐慌,这个编辑器也显得比较简陋。