gpt4 book ai didi

swiftui - 如何在 Swift UI 中不提供先前功能的情况下在自定义 View (ListRowView) 中添加按钮?

转载 作者:行者123 更新时间:2023-12-05 03:23:58 29 4
gpt4 key购买 nike

下面的代码运行良好,但我有一个问题,我不想在这里提供功能,我只想添加按钮 (dropDownButton) 并在使用此自定义 View 时提供功能。

struct DrawerItemListRowView: View {

@State var iconName: Icon
@State var text: String
@State var dropDownButton = Button(action: {}) {
Image(icon: .drawer)
}


var body: some View {

HStack(alignment: .center, spacing: 15) {

Image(icon: iconName)

Text(text)
.foregroundColor(.customLightBlack)
.font(.custom(ubuntu: .regular, style: .title2))

Spacer()

dropDownButton
.frame(width: 24, height: 24, alignment: .trailing)
}
.padding()
.listRowSeparator(.hidden)
.listRowBackground(Color.customBackground)
.background(Color.clear)
}
}

struct DrawerItemListRowView_Previews: PreviewProvider {
static var previews: some View {
Group {
DrawerItemListRowView(iconName: .mainCategory, text: "Shop by category")
DrawerItemListRowView(iconName: .paymentMethod, text: "Payment Methods")
}
.previewLayout(.sizeThatFits)
.background(.white)
} }

最佳答案

您需要传递操作,而不是按钮,类型为 ()->Void

看看这个例子:

struct DrawerItemListRowView: View {
let iconName: String
let text: String
let action: ()->Void // Pass the action, not the button

var body: some View {

HStack(alignment: .center, spacing: 15) {

Image(systemName: iconName)

Text(text)
.foregroundColor(.gray)

Spacer()

Button {
action() // Call the action
} label: {
Text(text)
.fixedSize()
}
.frame(width: 24, height: 24, alignment: .trailing)
}
.padding()
.listRowSeparator(.hidden)
.listRowBackground(Color.yellow)
.background(Color.clear)
}
}

struct Example: View {

var body: some View {
VStack {
DrawerItemListRowView(iconName: "house", text: "Shop by category") {
print("Bought")
}
DrawerItemListRowView(iconName: "minus", text: "Payment Methods") {
print("Paid")
}
}
.previewLayout(.sizeThatFits)
.background(.white)
}
}

关于swiftui - 如何在 Swift UI 中不提供先前功能的情况下在自定义 View (ListRowView) 中添加按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72402184/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com