如何在协议扩展中设置代理

3

我有多个视图控制器显示相同类型的单元格。我想在协议扩展中设置委托,就像这样:

class ProductsViewController: UIViewController, ProductShowcase {
    //other properties
    @IBOutlet weak var productCollectionView: UICollectionView!
    var dataSource: DataSource!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupDataSource()

        setupCollectionView()
    }

    func didSelectProduct(product: Product) {
        print(product)
    }

    //other functions
}

protocol ProductShowcase: UICollectionViewDelegate {
    var dataSource: DataSource! { get set }
    var productCollectionView: UICollectionView! { get }

    func didSelectProduct(product: Product)
}

extension ProductShowcase {
    func setupCollectionView() {
        productCollectionView.registerClass(ProductCollectionViewCell.self, forCellWithReuseIdentifier: "productCell")
        productCollectionView.dataSource = dataSource
        print(self) //prints ProductsViewController
        productCollectionView.delegate = self // 
        print(productCollectionView.delegate) //prints optional ProductsViewController
    }
}

extension ProductShowcase {
    //this delegate method is not called
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        didSelectProduct(dataSource.dataObjects[indexPath.row])
    }
}

didSelectItemAtIndexPathProductsViewController中被实现后,它会被调用。我是否漏掉了什么或者这种方法是错误的?


我相信你正在遇到当前Objective-C互操作性限制,该限制在此处描述:https://dev59.com/XFkS5IYBdhLWcg3ww49d#39604189 - Matthew Seaman
1个回答

3

这是Objective-C的互操作性限制。您不能像您想要的那样在协议扩展中实现带有可选函数的协议(来自Objective-C类型的UIKit控件的代理和数据源等协议)。您只能拥有写作如下的协议的默认实现:

// No, @objc in the front of protocol. (i.e. objc-type protocol)
protocol X {
}

将实现放在“protocol ProductShowcase: UICollectionViewDelegate”中是否可以解决问题?我在哪里可以阅读有关此Objective-C互操作性限制的信息?另外,请注意,在Swift 3中,我在那一行上得到了Segmentation Fault 11。 - osrl
它不能解决你的问题。唯一解决你的问题的方法是子类化。这里有一些限制:https://www.lynda.com/Swift-tutorials/Limitations-language-interoperability/185037/367698-4.html?certificate=CE455E2C8E994AB398FA5E8CA22AC26B - Bibek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接