首页 > 解决方案 > 如何在 WatchOS 中使用背景视图填充整个 Button 区域?

问题描述

我试图让我的背景视图跨越 Apple Watch 外形尺寸上按钮的整个区域。

struct SurveyView: View {

var body: some View {
    Button(action: {
        print("Test tapped.")
    }) {
        HStack {
            Text("Test")
                .fontWeight(.semibold)
        }
        .frame(minWidth: 0, maxWidth: .infinity)
        .padding()
        .foregroundColor(.white)
        .background(LinearGradient(gradient: Gradient(colors: [.green, .blue]), startPoint: .leading, endPoint: .trailing))


     }
   }
}

在此处输入图像描述

如何使背景跨越整个 Button?

更新:原来我的问题也与在列表视图中有关。设置蒙版并不能完全解决它。

struct SurveyView: View {

var body: some View {
    List() {
        Button(action: {
            print("Test tapped.")
        }) {
            Text("Test")
                .fontWeight(.semibold)
        }
        .background(Color.orange)


        .mask(RoundedRectangle(cornerRadius: 24))
        }
    }
}

在此处输入图像描述

标签: swiftswiftuiapple-watchwatchos

解决方案


我会通过以下方式做到这一点:

WatchKit 按钮的 SwiftUI 自定义背景

Button(action: {
    print("Test tapped.")
}) {
    Text("Test")
        .fontWeight(.semibold)
        .padding()
        .foregroundColor(.white)
}
.background(LinearGradient(gradient: Gradient(colors: [.green, .blue]), startPoint: .leading, endPoint: .trailing))
.mask(RoundedRectangle(cornerRadius: 24))

更新:列表的情况

var body: some View {
    List() {
        Button(action: {
            print("Test tapped.")
        }) {
            Text("Test")
                .fontWeight(.semibold)
                .padding()
        }
        .background(Color.orange)
        .mask(RoundedRectangle(cornerRadius: 24))
        .listRowPlatterColor(Color.clear)
    }
}

推荐阅读