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

时间:2019-12-15 05:52:58

标签: swiftui

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

  

enter image description here

我正在使用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: {})
    }
}

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

  

enter image description here

理想情况下,我想避免使用using an NSAttributedString,因为我想使用SwiftUI组件,而只希望蓝色部分是可轻敲的。

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

1 个答案:

答案 0 :(得分:0)

这种类型的布局不太可能很快在SwiftUI中提供。主要的复杂性来自于这样一个事实,即Button文本必须对Text块的框架有一定的了解(例如,要知道将诸如“数据”一词之类的溢出内容放在何处。原始示例),(B)将Button的第一个基线与Text的最后一个基线对齐,以及(C)将Button的前沿与精确的对齐Text的最后一行的结尾(例如,它不能仅位于框架的右侧,否则会出现HStack行为)。

一种解决方法是采用垂直放置组件的另一种模式(即Safari设置中的一种):

  

enter image description here

这是在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()
}