Error: Multiple inheritance from classes 'UICollectionViewController' and 'UICollectionViewLayout'

Error: Multiple inheritance from classes 'UICollectionViewController' and 'UICollectionViewLayout'

在 Xcode 8 中,我试图创建 UICollectionViewController 和 UICollectionViewLayout 的子类,但出现错误:

Multiple inheritance from classes 'UICollectionViewController' and 'UICollectionViewLayout'

但他们有不同的 parents 类。我正在尝试按照 http://nshint.io/blog/2015/07/16/uicollectionviews-now-have-easy-reordering/ 教程重新排序自定义大小的单元格

class WordCollectionViewController: UICollectionViewController, UICollectionViewLayout {
    // ...
    override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath], withTargetPosition targetPosition: CGPoint, previousIndexPaths: [IndexPath], previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
            var context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths, withTargetPosition: targetPosition, previousIndexPaths: previousIndexPaths, previousPosition: previousPosition)

        return context
    }
}

超出我的评论。 Swift 支持多重继承。 UICollectionViewLayout 是 class,因此由于您的 WorldCollectionViewController 已经继承自 UICollectionViewController,您不能继承自 UICollectionViewLayout(您也不想)。这个:

class ViewController: UIViewController, UITextFieldDelegate {

}

不是多重继承,而是来自 UIViewController 的单一继承,并且符合协议 UITextFieldDelegate

您可以在此处详细了解什么是协议以及如何使用它们:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

从本质上讲,协议就像一套指南。这些准则指定方法和属性。如果 class 符合 协议,则它必须实现协议指南中描述的方法和属性。例如:

protocol hasAVariablePotato {
   var potato: String! { get set }
}

任何符合此协议的对象 必须 有一个类型为 String 且隐式展开的变量(不是 let 常量)potato。像这样:

class PotatoFarmer: Farmer, hasAVariablePotato {

}

上面的PotatoFarmerclass继承自Farmerclass和但不符合hasAVariablePotato 因为没有potato var!所以上面会产生错误:

Type 'PotatoFarmer' does not conform to protocol 'hasAVariablePotato'

要修复此错误程序员必须在协议的属性和方法中添加,如下所示:

class PotatoFarmer: Farmer, hasAVariablePotato {
   var potato: String!
}

错误现在将消失,因为您符合协议。

根据您的情况,您希望将 UICollectionViewLayoutUICollectionViewLayoutAttributes 分开 classes。要查看如何执行此操作,请在此处查看(有关该主题的精彩免费教程): https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest

Swift 不支持多重继承。 UICollectionViewController 和 UICollectionViewLayout 都是 class。不要同时继承 class。您可以改用下面的代码

import Foundation
import UIKit

class Test:UICollectionViewLayout{

    override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath], withTargetPosition targetPosition: CGPoint, previousIndexPaths: [IndexPath], previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
        var context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths, withTargetPosition: targetPosition, previousIndexPaths: previousIndexPaths, previousPosition: previousPosition)

            return context
    }
}