SwiftUI - 多行文本后跟按钮

问题描述 投票:0回答:2

我们如何设计多行文本和按钮。我尝试使用以下代码片段,文本和按钮水平放置。

        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 应该是可点击的并且具有点击效果。

预期输出

ios swift swiftui
2个回答
2
投票

这可以通过将

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()
}

结果: enter image description here


0
投票

使用

Text(.init(["KEY"]("Click here"))
并使用
.environment(.\openURL, _)
访问“KEY”以使该文本可点击。

Multiline_text_with_action

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
        })
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.