You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何读取ScrollView内项目的当前位置?

解决方案

核心逻辑很简单:你实现的拖拽排序已经直接修改了LAPutDialogueInOrderVM.dialogueBoxes数组的顺序,数组的当前索引就是对话框在ScrollView里的实际位置,不需要额外从ScrollView获取位置。

具体实现步骤

1. 确保dialogueBox模型包含正确位置属性

你的dialogueBox结构体需要有存储正确位置的属性,示例如下:

struct dialogueBox: Identifiable {
    let id: UUID
    let dialogueText: String
    let correctPosition: Int // 存储正确的位置索引(注意和数组索引计数保持一致,建议从0开始)
}

2. 添加排序验证逻辑

直接在test按钮的action中添加验证逻辑,遍历数组对比每个元素的当前索引与正确位置:

Button(action: {
    var isAllCorrect = true
    for (currentIndex, item) in LAPutDialogueInOrderVM.dialogueBoxes.enumerated() {
        // 若你的correctPosition是从1开始计数,需改为currentIndex == item.correctPosition - 1
        if currentIndex != item.correctPosition {
            isAllCorrect = false
            print("第\(currentIndex+1)个对话框位置错误,正确位置应为\(item.correctPosition+1)")
            break
        }
    }
    
    if isAllCorrect {
        print("排序完全正确!")
        // 此处添加排序正确后的逻辑,比如提交结果、显示成功提示
    } else {
        print("排序有误,请检查")
        // 此处添加错误提示逻辑
    }
}, label: {
    Text("验证排序")
})

3. (可选)将验证逻辑封装到ViewModel

为了代码结构更清晰,可把验证逻辑迁移到LAPutDialogueInOrderViewModel中:

class LAPutDialogueInOrderViewModel: ObservableObject {
    @Published var dialogueBoxes: [dialogueBox] = []
    
    // 已有初始化方法...
    
    func checkSortingIsCorrect() -> Bool {
        return dialogueBoxes.enumerated().allSatisfy { currentIndex, item in
            currentIndex == item.correctPosition
        }
    }
}

之后按钮中只需调用该方法:

Button(action: {
    let isCorrect = LAPutDialogueInOrderVM.checkSortingIsCorrect()
    if isCorrect {
        print("排序正确")
    } else {
        print("排序错误")
    }
}, label: {
    Text("验证排序")
})

关键说明

  • 拖拽排序时,你的DropViewDelegate已经在修改dialogueBoxes数组的顺序,因此数组顺序完全对应ScrollView内的显示顺序,直接用数组索引即可代表当前位置。
  • 注意索引计数一致性:Swift数组索引从0开始,若你的correctPosition是按1开始标记的,需在对比时做减1转换。

内容的提问来源于stack exchange,提问作者mzm0227

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:44:54