我们如何设计多行文本和按钮。我尝试使用以下代码片段,文本和按钮水平放置。
HStack {
Text("Very long text Very long text Very long text Very long text Very long text")
Button {
} label: {
Text("Click here")
Image(uiImage: UIImage.add)
}
}
只有 Button 应该是可点击的并且具有点击效果。
这可以通过将
label
更改为 Button
来实现,如下所示。
代码:
var body: some View {
VStack {
Button(action: {
let tosURL = URL.init(string: "https://www.google.com")! // add your link here
if UIApplication.shared.canOpenURL(tosURL) {
UIApplication.shared.open(tosURL)
}
}, label: {
(Text("Very long text Very long text Very long text Very long text Very long text gte wkjeh ") +
Text("Click here")
.foregroundColor(.blue)
.underline()
)
.frame(maxWidth: .infinity, alignment: .leading)
.font(Font.system(size: 14, weight: .medium))
.foregroundColor(Color.black)
.fixedSize(horizontal: false, vertical: true)
})
.padding([.horizontal], 20)
}
.padding()
}
使用
Text(.init(["KEY"]("Click here"))
并使用 .environment(.\openURL, _)
访问“KEY”以使该文本可点击。
enum NavigationKey {
static let welcome = "CLICK_HERE_KEY"
}
struct ContentView: View {
let actionKey = "[Click here](\(NavigationKey.welcome))"
var body: some View {
VStack {
Text("`Hello, World!` phrase that is written in a multiline text with some extra description. The description is not clickable, just a button. ") +
Text(.init(actionKey))
.underline()
}
.tint(.pink)
.padding()
.environment(\.openURL, OpenURLAction { url in
if url.description == NavigationKey.welcome {
print("`Click here` pressed")
}
return .discarded
})
}
}