SwiftUI – 多行文本后跟按钮

huangapple go评论61阅读模式
英文:

SwiftUI - Multi line text followed by button

问题

HStack {
    Text("非常长的文本 非常长的文本 非常长的文本 非常长的文本 非常长的文本")
    Button {
        
    } label: {
        Text("点击这里")
        Image(uiImage: UIImage.add)
    }
}

按钮应该是唯一可点击的,带有点击效果。

英文:

How can we design multiline text followed by button. I tried with the following snippet, text and button are placed horizontal.

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

Only Button should be clickable with click effect.

Expected OUTPUT

答案1

得分: 1

这可以通过将更改后的label提供给Button来实现,如下所示。

代码:

var body: some View {
    VStack {
        Button(action: {
            let tosURL = URL.init(string: "https://www.google.com")! // 在此添加您的链接
            if UIApplication.shared.canOpenURL(tosURL) {
                UIApplication.shared.open(tosURL)
            }
        }, label: {
            (Text("非常长的文本 非常长的文本 非常长的文本 非常长的文本 非常长的文本 gte wkjeh ") +
             Text("点击这里")
                .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()
}

结果:
SwiftUI – 多行文本后跟按钮

英文:

This can be achieved by providing altered label to Button, as shown bellow.

Code:

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

Result:
SwiftUI – 多行文本后跟按钮

huangapple
  • 本文由 发表于 2023年6月26日 22:59:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定