在 Swift 中继承 UITapGestureRecognizer
Subclassing UITapGestureRecognizer in Swift
我想子class UITapGestureRecognizer
为 TapRecognizer
以便以标准化方式处理我的应用程序中页面之间的导航:
- 将
UITapGestureRecognizer
拖到故事板中的任何导航元素上,将它们的 class 设置为 TapRecognizer
,并在视图控制器中将它们引用为 IBOutlet (@IBOutlet var heroTapRecognizer: TapRecognizer!
)
像这样初始化它们:
self.heroTapRecognizer = TapRecognizer.init(pageId: 1, pageType: PageType.CategoryPage)
然后在TapRecognizer.swift:
class TapRecognizer: UITapGestureRecognizer {
var pageId:Int!
var pageType:PageType!
convenience init(pageId: Int, pageType: PageType) {
self.init()
self.pageId = pageId
self.pageType = pageType
self.addTarget(self, action: #selector(TapRecognizer.handleTap(_:)))
}
func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
print("Handle navigation based on pageId + pageType")
}
}
}
但是上面的方法不起作用。我是 Swift 的新手,之前只以编程方式使用过 UITapGestureRecognizer
。
注意:在识别器关联的 UIView
上启用了用户交互 。
Dragging a UITapGestureRecognizer onto any navigational elements in the storyboard, setting their class as TapRecognizer, and referencing them within the View Controller as an IBOutlet
好的,但是您的 init
将永远不会被调用。如果您希望发生一些特别的事情,请实施 awakeFromNib
.
或者,实施 init(coder:)
。由于某种原因,这没有记录在案,但实际调用的是初始化程序。
我想子class UITapGestureRecognizer
为 TapRecognizer
以便以标准化方式处理我的应用程序中页面之间的导航:
- 将
UITapGestureRecognizer
拖到故事板中的任何导航元素上,将它们的 class 设置为TapRecognizer
,并在视图控制器中将它们引用为 IBOutlet (@IBOutlet var heroTapRecognizer: TapRecognizer!
) 像这样初始化它们:
self.heroTapRecognizer = TapRecognizer.init(pageId: 1, pageType: PageType.CategoryPage)
然后在TapRecognizer.swift:
class TapRecognizer: UITapGestureRecognizer {
var pageId:Int!
var pageType:PageType!
convenience init(pageId: Int, pageType: PageType) {
self.init()
self.pageId = pageId
self.pageType = pageType
self.addTarget(self, action: #selector(TapRecognizer.handleTap(_:)))
}
func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
print("Handle navigation based on pageId + pageType")
}
}
}
但是上面的方法不起作用。我是 Swift 的新手,之前只以编程方式使用过 UITapGestureRecognizer
。
注意:在识别器关联的 UIView
上启用了用户交互 。
Dragging a UITapGestureRecognizer onto any navigational elements in the storyboard, setting their class as TapRecognizer, and referencing them within the View Controller as an IBOutlet
好的,但是您的 init
将永远不会被调用。如果您希望发生一些特别的事情,请实施 awakeFromNib
.
或者,实施 init(coder:)
。由于某种原因,这没有记录在案,但实际调用的是初始化程序。