Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moment: ForEach(), Index out of range #6

Closed
Haibo-Zhou opened this issue Mar 20, 2020 · 8 comments
Closed

Moment: ForEach(), Index out of range #6

Haibo-Zhou opened this issue Mar 20, 2020 · 8 comments

Comments

@Haibo-Zhou
Copy link

Haibo-Zhou commented Mar 20, 2020

感谢分享,
ForEach<Range<Int>, Int, ModifiedContent<ModifiedContent<ModifiedContent<Image, _AspectRatioLayout>, _FrameLayout>, _ClipEffect<Rectangle>>> count (2) != its initial count (3). ForEach(:content:)should only be used for *constant* data. Instead conform data toIdentifiableor useForEach(🆔content:)and provide an explicitid!

我在真机上运行发现朋友圈View下拉会导致数组越界,在ForEach里面加上id参数可以解决这个问题。
e.g.
ForEach(0 ..< rows, id: \.self)

@wxxsw
Copy link
Owner

wxxsw commented Mar 20, 2020

好的谢谢,我周末改一下

@Haibo-Zhou
Copy link
Author

Haibo-Zhou commented Mar 22, 2020 via email

@wxxsw
Copy link
Owner

wxxsw commented Mar 22, 2020

知道位置了,已经改了~

因为图片宫格这里布局的关系,需要遍历行和列,就用的 Range 去迭代了,所以主要修改就是如你所说,加上了 id: \.self

至于数组越界的代码 self.images[row * self.cols + col],我检查了一下,觉得不是计算的问题,猜测可能还是上面的问题导致的,我这里复现不了,你可以试一下哈

@Haibo-Zhou
Copy link
Author

Haibo-Zhou commented Mar 22, 2020 via email

@wxxsw
Copy link
Owner

wxxsw commented Mar 22, 2020

之前确实没考虑 SE,这个问题我的解决方法如下:

func rowBody(row: Int, isLast: Bool) -> some View {
    HStack(spacing: 6) {
        ForEach(0 ..< (isLast ? self.lastRowCols : self.cols), id: \.self) { col in
            Image(self.images[row * self.cols + col].cover)
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(minWidth: 60, maxWidth: 80, minHeight: 60, maxHeight: 80)
                .aspectRatio(1, contentMode: .fill)
                .clipped()
        }
    }
}

主要的知识点是:
1.固定宽高改为设置宽高范围,最小宽度 60 能保证 SE 上正常显示
2.由于图片宽高不固定,导致宽高可能不同,所以需要约束宽高比是 1:1
3.第一个 aspectRatio 是限制图片需要按照原比例缩放,避免拉伸失真,第二个 aspectRatio 是限制控件按照 1:1 展示

如果再有不同的问题,可以开新的 issue 哈

@wxxsw wxxsw closed this as completed Mar 24, 2020
@Haibo-Zhou
Copy link
Author

Haibo-Zhou commented Mar 25, 2020 via email

@wxxsw
Copy link
Owner

wxxsw commented Mar 25, 2020

好的,上一个评论有更新留意下,祝找到心仪的工作

@Haibo-Zhou
Copy link
Author

Haibo-Zhou commented Mar 25, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants