我的应用程序位于 UIKit 中。
我正在为我的应用程序开发一个中等大小的小部件。该小部件是使用 SwiftUI 创建的。该小部件包含三个按钮,每个按钮都用于将用户导航到应用程序内的特定屏幕。
目前,我的小部件的设计看起来不错,并且可以正确显示在主屏幕上。但是,当我点击三个按钮中的任何一个时,按钮单击事件似乎不起作用。
当我点击一个按钮时,整个小部件都会被点击。但是,我想单独区分和管理三个按钮中每个按钮的点击事件。
我已经提到了this,但这不起作用
这是我的代码:
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
}
}
Widget 按钮点击可以使用 AppIntent 处理: 创建一个 swift 文件 ViewContactsAppIntent.swift
import Foundation
import AppIntents
struct ViewContactsAppIntent: AppIntent {
static var title: LocalizedStringResource = "View Contacts Clicked"
init(){}
func perform() async throws -> some IntentResult {
print("Button Clicked*******: ")
return .result()
}
}
像这样使用AppIntent:
Button(intent: ScanButtonIntent()) {
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: 15, height: 15)
.foregroundStyle(.black)
Spacer()
}
}
.buttonStyle(.plain)