【问题标题】:How to add a Button to the end of Text in SwiftUI?如何在 SwiftUI 中的文本末尾添加一个按钮?
【发布时间】:2019-12-15 14:03:26
【问题描述】:

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

我正在使用 SwiftUI。我尝试以多种方式结合TextButton

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: {})
    }
}

但是这些组合都不起作用:

我最好避免使用using an NSAttributedString,因为我想使用 SwiftUI 组件,并且只希望蓝色部分是可点击的。

如何将Button 附加到Text 以使其文本与文本的基线对齐?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    这种类型的布局不太可能很快在 SwiftUI 中可用。主要的复杂性来自Button 文本必须对(A)Text 块的框架有一些了解(例如,要知道在哪里放置溢出的内容,如原始示例中的单词“data”), (B) 将Button 的第一个基线与Text 的最后一个基线对齐,(C) 将Button 的前沿与最后一行Text 的确切末尾对齐(例如,它不能只是在框架的右侧,否则你会得到 HStack 行为)。

    一种解决方法是遵循垂直放置组件的不同模式(即 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()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 2022-07-28
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多