SwiftUI如何在TextView中添加下划线?

33

有没有办法将TextView修改为带有下划线的文本?例如像下面这个文本:

y͟o͟u͟r͟ t͟e͟x͟t͟

Text(Constants.chooseText)
    .font(Font.system(size: 26))
    .foregroundColor(Color.white)
    .padding(.bottom, 80)
4个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
92
在文本视图上添加下划线修饰符。
        Text("Hello, world!")
            .underline()

1
下划线在iOS 16之后可用。如果我们需要在iOS 16之前使用该功能,应该怎么办? - Pooja Gupta
2
@PoojaGupta 自iOS 13.0+版本以来,下划线功能已经可用。https://developer.apple.com/documentation/swiftui/text/underline(_:color:) - byaruhaf
1
@PoojaGupta是正确的!看这个:https://developer.apple.com/documentation/swiftui/view/underline(_:pattern:color:) - Mannopson

13

加入underline()作为第一个修改器解决了这个问题。

Text(Constants.chooseText)
    .underline()
    .font(Font.system(size: 26))
    .foregroundColor(Color.white)
    .padding(.bottom, 80)

6

iOS 16 如果您想使用下划线修饰符,可以使用underline。如果您需要更高级的控制,例如控制其位置和大小,则可以使用background修饰符,在背景中设置下划线的高度偏移量颜色。或者,您也可以使用overlay修饰符。示例代码:

// Using background modifier
                    Text("FRANCE")
                        .foregroundColor(Color.white)
                        .background(
                            Color.white
                                .frame(height: 1) // underline's height
                                .offset(y: 14) // underline's y pos
                        )

输出: 在此输入图像描述

//Using overlay modifier
              Text("FRANCE")
                        .foregroundColor(Color.white)
                        .overlay(
                            Rectangle()
                                .fill(Color.white)
                                .frame(width: 64, height: 1)
                            , alignment: .bottom
                        )

输出:在此输入图像描述


4

您可以像下面这样使用:

Text("Forget User ID")
     .underline(true, color: .gray)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,