获取 UITapGestureRecognizers 目标

Getting a UITapGestureRecognizers Target

我正在尝试创建一个基本视图,其 backgroundColor 每次被点击时都会在两种颜色之间切换。为了实现这一点,我创建了一个函数,它将要更改的视图和要切换的两种颜色作为参数。

为此,我需要传递它应该更改的 UIView。但是 UIViews 本身无法识别触摸,所以我 "linked"(我不确定我是否理解正确)一个 UITapGestureRecognizer 到它触发我的 ViewController 中的一个动作。

现在我需要链接 UITapGestures UIView 以便我可以更改它。

我知道我可以简单地将相应的 UIView 输入到操作中,但我想让这个功能尽可能灵活(只是想从正确的礼仪开始)。

这是我的不完整函数:

@IBAction func colorViewTapped(_ sender: Any) {
    print("tap")
    //Heres the problem: I get an "Cannot convert value of type 'Any' to expected argument type 'UIView'
    toggleViewBackgroundColor(view: sender, color1: UIColor.blue, color2: UIColor.brown)
}

将您的操作方法参数类型从 Any 更改为 UITapGestureRecognizer,然后使用 UIGestureRecognizerview 属性 来获取点击视图的引用。

@IBAction func colorViewTapped(_ sender: UITapGestureRecognizer) {
    print("tap")
    toggleViewBackgroundColor(view: sender.view!, color1: UIColor.blue, color2: UIColor.brown)
}