UIKit应用SwiftUI中型Widget按钮点击失效求助
Widget按钮点击事件失效,无法独立触发操作
我的应用基于UIKit开发,使用SwiftUI开发了一款中型Widget,Widget内包含三个按钮,每个按钮的作用是将用户导航至App内的指定页面。
目前Widget外观显示正常,主屏幕上能正确展示,但点击任意按钮时,按钮的点击事件均未生效,反而整个Widget会被触发,我需要实现分别识别并处理三个按钮的独立点击事件,尝试过相关方案但未解决问题。
以下是我的代码:
struct appWidgetEntryView: View { @Environment(\.widgetFamily) var widgetFamily var body: some View { Group { if widgetFamily == .systemMedium { RectangleWidgetView() //This is medium widget view } } } } struct RectangleWidgetView: View { var body: some View { VStack(spacing: 8){ //button 1 (View contacts) Button(action: { // Action print("****View Contacts Clicked*****") }) { HStack(spacing: 4) { Spacer() Text("View Contacts") .font(.system(size: buttonFontSize)) .fontWeight(.medium) .foregroundStyle(.black) .frame(height: buttonHeight) .lineLimit(2) Image("contacts") .resizable() .scaledToFit() .frame(width: 20, height: 20) .foregroundStyle(.black) Spacer() } } .buttonStyle(.plain) .frame(maxWidth: .infinity, alignment: .center) //button 2 (Add Contacts) Button(action: { UserDefaults(suiteName: WidgetKitManager.Name.appGroup.rawValue)?.setValue("AddContact", forKey: "widgetAction") print("****Add contact Clicked*****") }) { HStack(spacing: 4) { Spacer() Text("Add Contact") .font(.system(size: buttonFontSize)) .fontWeight(.medium) .foregroundStyle(.black) .frame(height: buttonHeight) .lineLimit(2) Image("float_add") .resizable() .scaledToFit() .frame(width: 15, height: 15) .foregroundStyle(.black) Spacer() } } .buttonStyle(.plain) .frame(maxWidth: .infinity, alignment: .center) //button 3 (Delete Contact) Button(action: { UserDefaults(suiteName: WidgetKitManager.Name.appGroup.rawValue)?.setValue("deleteContact", forKey: "widgetAction") print("****Delete contact Clicked*****") }) { HStack(spacing: 4) { Spacer() Text("Delete Contact") .font(.system(size: buttonFontSize)) .fontWeight(.medium) .foregroundStyle(.black) .frame(height: buttonHeight) .lineLimit(2) Image("float_add") .resizable() .scaledToFit() .frame(width: 15, height: 15) .foregroundStyle(.black) Spacer() } } .buttonStyle(.plain) .frame(maxWidth: .infinity, alignment: .center) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(widgetBGColor) .cornerRadius(12) .adoptableWidgetBackground(widgetBGColor) // Add this line } }
内容的提问来源于stack exchange,提问作者Monika Patel
相关产品推荐
相关产品推荐

