ios - 如何传入带delegate的对象

标签 ios swift uiapplicationdelegate

快速搜索这个问题没有给我任何结果。同时也不好解释,我想从这个方法就一切都清楚了。请看看这个:

func tap(sender: AnyObject, action: Selector) -> UITapGestureRecognizer {
        let tap = UITapGestureRecognizer(target: sender, action: action)
        tap.delegate = sender
        return tap
    }

错误:

Type 'AnyObject' does not conform to protocol 'UIGestureRecognizerDelegate'

问题是需要为 AnyObject 编写什么来避免收到此消息?还是其他方式?

最佳答案

假设 sender 始终是 UIGestureRecognizerDelegate 类型,您可以使用强制向下转换:

tap.delegate = sender as UIGestureRecognizerDelegate

否则,使用失败的转换:

if let delegate = sender as? UIGestureRecognizerDelegate
{
    tap.delegate = delegate
}

作为引用,看看Type Casting for Any and AnyObject包含在 Swift 编程语言指南中。

请注意,对我来说,这种分配委托(delegate)的方式似乎不寻常且容易出错。

关于ios - 如何传入带delegate的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28833438/

相关文章:

ios - 尝试根据设备的角度旋转图像

ios - TableView Swift 3 中的不同单元格

ios - LazyVGrid 中的 SwiftUI 中心项目

ios - 如何 "restart"iOS 应用程序/从 UIApplicationDelegate 实例重新实例化初始 View Controller ?

ios - 我可以使用一个自定义创建的 UIViewController 来填充父 UITableViewController 的单元格文本值吗?

ios - 背景图片大小 Sprite Kit Game

ios - 无法在 Swift 中使用协议(protocol)作为另一个协议(protocol)中的关联类型

android - 电晕与 Xamarin?我应该拿起什么?

iphone - iOS 会在后台杀死应用程序吗?

ios - UITextField 不显示键盘