widgetURL是否在Foreach中被覆盖?

时间:2020-10-14 01:10:19

标签: ios arrays swiftui widgetkit

我在iOS 14中型窗口小部件中显示3行,如下所示:

 row 1
-------
 row 2
-------
 row 3
-------

我的视图结构在这里:

VStack {
    ForEach(records, id: \.id) { item in 
        ZStack {
            // some views
        }
        .widgetURL(URL(string: "wig://\(item.id)"))
    }
    Divider()
}

第一第二项目的窗口小部件URL似乎被第三项目覆盖,所有深层链接将打开第三项目的内容。

为从ForEach生成的视图添加深层链接的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

这是接口合同(请注意标记处)

    /// Sets the URL to open in the containing app when the user clicks the widget.
    /// - Parameter url: The URL to open in the containing app.
    /// - Returns: A view that opens the specified URL when the user clicks
    ///   the widget.
    ///
>>    /// Widgets support one `widgetURL` modifier in their view hierarchy.
>>    /// If multiple views have `widgetURL` modifiers, the behavior is
    /// undefined.
    public func widgetURL(_ url: URL?) -> some View

相反,您必须使用Link,例如

    ForEach(records, id: \.id) { item in 
       Link(destination: URL(string: "wig://\(item.id)")!) {
         ZStack {
            // some views
         }
       }
    }