微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI 中 ForEach 和 NavigationLink 的问题

如何解决SwiftUI 中 ForEach 和 NavigationLink 的问题

这是我遇到问题的基本代码片段:

import SwiftUI

struct ContentView: View {
    var pets = ["Dog","Cat","Rabbit"]
    var body: some View {
    NavigationView {
        List {
            ForEach(pets,id: \.self) {
                NavigationLink(destination: Text($0)) {
                    Text($0)
                }
            }
        }
        .navigationBarTitle("Pets")
    }
}

我收到错误

未能产生表达诊断;请提交错误报告

我的目的是熟悉 NavigationLink,并导航到一个页面,该页面仅在单击项目时显示文本。

任何帮助将不胜感激。

解决方法

nicksarno 已经回答了,但既然你评论了你不明白,我会试一试。

$0 引用当前闭包中没有命名的第一个参数。

ForEach(pets,id: \.self) {
    // $0 here means the first argument of the ForEach closure
    NavigationLink(destination: Text($0)) {
        // $0 here means the first argument of the NavigationLink closure 
        // which doesn't exist so it doesn't work
        Text($0)
    }
}

解决方案是用 <name> in

命名参数
ForEach(pets,id: \.self) { pet in
    // now you can use pet instead of $0
    NavigationLink(destination: Text(pet)) {
        Text(pet)
    }
}

注意;你得到这个奇怪错误的原因是它找到了一个不同的 NavigationLink init,它确实有一个带参数的闭包。

,

它与您使用的速记初始值设定项有关。这些替代方案中的任何一个都可以:

const GRID_SIZE = 50;

shape.on('transform',() => {
  shape.x(Math.round(shape.x() / GRID_SIZE) * GRID_SIZE);
  shape.y(Math.round(shape.y() / GRID_SIZE) * GRID_SIZE);
  

  const width = shape.width() * shape.scaleX();
  const roundedWidth = Math.round(width / GRID_SIZE) * GRID_SIZE;
  if (roundedWidth !== 0) {
    shape.scaleX(roundedWidth / shape.width())
  }

  const height = shape.height() * shape.scaleY();
  const roundedHeight = Math.round(height / GRID_SIZE) * GRID_SIZE;
  if (roundedHeight !== 0) {
    shape.scaleY(roundedHeight / shape.width())
  }
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。