通过协议委派行动不迅速 [英] Delegating action through protocol not working swift
问题描述
我需要将 UIView
类的点击操作委托给我的 UIViewController
类,因为 Swift 不支持多类继承.所以我想要它,一旦在我的子视图上单击一个按钮,我的 BrowserViewController
类中的一个函数就会被调用.
I needed to delegate a click action for my UIView
class to my UIViewController
class since Swift does not support multiple class inheritance. So i wanted it such that once a button is clicked on my subview, a function in my BrowserViewController
class is called.
我正在使用 protocol
来实现这一点,但在点击按钮时不会触发该功能.请帮帮我.
I am using a protocol
to achieve this, but on the function does not triggered when the button is tapped. Please help me out.
视图控制器
class BrowseViewController: UIViewController {
var categoryItem: CategoryItem! = CategoryItem() //Category Item
private func setupExplore() {
//assign delegate of category item to controller
self.categoryItem.delegate = self
}
}
// delegate function to be called
extension BrowseViewController: ExploreDelegate {
func categoryClicked(category: ProductCategory) {
print("clicked")
let categoryView = ProductByCategoryView()
categoryView.category = category
categoryView.modalPresentationStyle = .overCurrentContext
self.navigationController?.pushViewController(categoryView, animated: true)
}
}
Explore.swift(子视图)
import UIKit
protocol ExploreDelegate: UIViewController {
func categoryClicked(category: ProductCategory)
}
class Explore: UIView {
var delegate: ExploreDelegate?
class CategoryItem: UIView {
var delegate: ExploreDelegate?
var category: ProductCategory? {
didSet {
self.configure()
}
}
var tapped: ((_ category: ProductCategory?) -> Void)?
func configure() {
self.layer.cornerRadius = 6
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.categoryTapped)))
self.layoutIfNeeded()
}
@objc func categoryTapped(_ sender: UIGestureRecognizer) {
delegate?.categoryClicked(category: ProductCategory.everything)
self.tapped?(self.category)
}
}
}
推荐答案
只需在categoryTapped内添加打印语句即可.
Simply add a print statement inside categoryTapped.
然后你就会知道它是否真的被窃听了.
You will then know if it is actually being tapped.
一百万件事情都可能出错,例如,您可能忘记设置 UIView 以允许交互.
A million things could go wrong, for example, you may have forget to set the UIView to allow intertaction.
检查后.接下来在 categoryTapped 中添加另一个打印语句, 显示delegate
变量是否为空.
After checking that. Next add another print statement inside categoryTapped which shows you whether or not the delegate
variable is null.
您可以使用简单的打印语句快速发现问题.
You'll quickly discover the problem using simple print statements.
print("I got to here!")
就这么简单.
然后呢
if delegate == nil { print("it is nil!! oh no!" }
else { print("phew. it is NOT nil.") }
在这个级别上调试真的很容易.
Debugging is really that easy at this level.
接下来添加打印语句inside setupExplore()
func setupExplore() {
print("setup explore was called")
....
看看会发生什么.
这篇关于通过协议委派行动不迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!