iOS Swift 4屏幕游戏刷卡盒

问题描述 投票:-2回答:1

我正在创建一个应用程序,以便用户必须从屏幕上滑动所有框。目标是刷所有方框,直到所有方框都被刷过,如下图所示。

Example that is made with buttons and UIStackView所以我的问题是:

  1. 使用“堆栈视图”创建框或者通过屏幕上的坐标手动绘制是否更好?
  2. 如何检测用户是否已刷过框(使用UIGestureRecognizer)?

注意:当用户刷过盒子时,刷盒会变成其他颜色。

ios swift iphone uigesturerecognizer
1个回答
0
投票

堆栈视图或手动应该很好地工作。在这种情况下我会手动使用,但这只是一个偏好,因为你可能对它有更多的权力。但是,当屏幕尺寸发生变化时,您需要重新定位它们。第三个选项也是集合视图。

手势识别器应该非常直接。您只需将它添加到这些单元格的超级视图中,并检查它移动时的位置或启动时的位置。平移手势似乎是最合适的,但它不会检测用户是否只是点击屏幕。这可能是一个功能,但如果你想处理所有的触摸,你应该使用长按手势,按下持续时间为零(这没有多大意义,我知道,但它的工作原理),或者你可能只是覆盖触摸方法:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        handleDrag(at: touch.location(in: viewWhereAllMiniViewsAre))
    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        handleDrag(at: touch.location(in: viewWhereAllMiniViewsAre))
    }
}

func handleDrag(at location: CGPoint) {
    // TODO: handle the nodes
}

手势识别器程序将执行以下操作:

func onDrag(_ sender: UIGestureRecognizer) {
    switch sender.state {
    case .began, .changed, .ended, .cancelled: handleDrag(at: sender.location(in: viewWhereAllMiniViewsAre))
    case .possible, .failed: break
    }
}

现在您只需要数据源。所有项目的数组应该足够了。喜欢:

static let rows: Int = 10
static let columns: Int =  10

var nodes: [Node] = {
    return Array<Node>(repeating: Node(), count: LoginViewController.rows * LoginViewController.columns)
}()

以及所有迷你视图的列表:

var nodeViews: [UIView] = { ... position them or get them from stack view or from collection view }

现在触摸手柄的实现:

func handleDrag(at location: CGPoint) {
    nodeViews.enumerated().forEach { index, view in
        if view.frame.contains(location) {
            view.backgroundColor = UIColor.green
            nodes[index].selected = true
        }
    }
}

这只是一个例子。从维护角度来看,这是一个简单的,而不是一个坏的。一般来说,我宁愿拥有自定义UIView子类的节点视图,其中包含对节点的引用。此外,它应该使用委托挂钩到Node实例,以便节点报告选择状态何时更改。

这样,在处理触摸时,您可以获得更清晰的解决方案:

func handleDrag(at location: CGPoint) {
    nodeViews.first(where: { $0.frame.contains(location) }).node.selected = true
}

然后检查是否所有都是绿色

var allGreen: Bool {
    return !nodes.contains(where: { $0.selected == false })
}
© www.soinside.com 2019 - 2024. All rights reserved.