如果标签落在错误的目标上,如何触发通知?

How to trigger a notification if label is dropped on wrong target?

在此拖放游戏 (adapted from this tutorial) 中,玩家必须将标签与正确的目标相匹配。我已将其设置为如果触摸结束并且标签的中心位于目标内,则它会从屏幕上移除并重新开始游戏。

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

  if label.name == "letters" {
    if lettersBin.frame.contains(label.position) {
        // remove it and create a new label
        label.removeFromParent()
        setupDragLabel()

但是,如果玩家将错误的标签放到垃圾桶上,我想触发通知,所以:

else if label.name == "numbers" {
 if lettersBin.contains(label.position) ...

我会写什么来完成这个?我是否让另一个标签出现在屏幕上?

使用 UIAlertController 可能是最简单的。您可以添加消息以及按钮操作以显示用户错误。

let converterAction = UIAlertController(title: "Your title here", message: "Your message to the user here", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default){ _ in
    //Any custom action to happen here
}
converterAction.addAction(okAction)

present(converterAction, animated: true, completion: nil)

如果您不想显示警报,您可以执行以下操作:

  1. 向故事板和您的文件添加标签。
  2. 将该标签设置为默认隐藏。
  3. 以编程方式设置 label.isHidden = false 并根据需要设置文本。

我现在标记为 "label" 的内容可以是任何内容,您甚至可以创建一组视图并一次性 hide/show 它们。当想要同时显示进度指示器和 "Loading..." 标签时很有用。