如何在 SwiftUI 中的文本末尾添加按钮?

Sen*_*ful 9 swiftui

我想在游戏中心设置中创建一个类似于 Apple 的 UI,其中文本末尾有一个可点击的链接:

在此输入图像描述

我正在使用 SwiftUI。我尝试以多种方式结合Text和:Button

Form {
    Text("A social gaming service that lets you interact with friends, track and compare scores and achievements, challenge other players, and compete in mulitplayer games.")
    Button("See how your data is managed...", action: {})

    Button(action: {}, label: {
        Text("A social gaming service that lets you interact with friends, track and compare scores and achievements, challenge other players, and compete in mulitplayer games.").foregroundColor(.black)
        Text("See how your data is managed...")
    })

    Group {
        Text("A social gaming service that lets you interact with friends, track and compare scores and achievements, challenge other players, and compete in mulitplayer games.")
        Button("See how your data is managed...", action: {})
    }

    HStack {
        Text("A social gaming service that lets you interact with friends, track and compare scores and achievements, challenge other players, and compete in mulitplayer games.")
        Button("See how your data is managed...", action: {})
    }
}
Run Code Online (Sandbox Code Playgroud)

但这些组合都不起作用:

在此输入图像描述

我理想地希望避免使用 NSAttributedString,因为我想使用 SwiftUI 组件,并且只希望蓝色部分可点击。

如何附加 aButton使其Text文本与文本的基线对齐?

Sen*_*ful 3

这种类型的布局不太可能很快在 SwiftUI 中可用。主要的复杂性来自于以下事实:文本Button必须了解以下内容:(A) 块的框架Text(例如,知道在哪里放置溢出内容,如原始示例中的“数据”一词),(B) 对齐块的框架。Button的第一条基线到 的最后一条基线,并且 (C) 将的前缘与最后一行的精确末端Text对齐(例如,它不能仅位于框架的右侧,否则您会得到HStack 行为)。ButtonText

一种解决方法是遵循一种不同的模式(即 Safari 设置中的模式),其中组件垂直放置:

在此输入图像描述

这是在 SwiftUI 中更容易实现的布局:

Section(footer:
    VStack(alignment: .leading) {
        Text("Allow websites to check if Apple Pay is enabled and if you have an Apple Card account.")
        Button("About Safari & Privacy...", action: {})
}) {
    EmptyView()
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

3410 次

最近记录:

5 年,10 月 前