错误:类'UICollectionViewController'和'UICollectionViewLayout'的多重继承

时间:2016-06-26 17:17:06

标签: ios swift class inheritance xcode8

在Xcode 8中,我正在尝试创建UICollectionViewController和UICollectionViewLayout的子类,但是我收到了错误:

  

来自类'UICollectionViewController'和'UICollectionViewLayout'的多重继承

但他们有不同的父母类。我正在尝试按照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
    }
}

2 个答案:

答案 0 :(得分:2)

超出我的评论。 Swift 不支持支持多重继承。 UICollectionViewLayout是一个类,因为WorldCollectionViewController已经从UICollectionViewController继承,您无法继承UICollectionViewLayout(您也不想)。这样:

class ViewController: UIViewController, UITextFieldDelegate {

}

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

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

基本上协议就像一套指导方针。这些准则指定了方法和属性。如果类符合协议,那么它必须实现协议指南中描述的方法和属性。例如:

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

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

class PotatoFarmer: Farmer, hasAVariablePotato {

}

上述PotatoFarmer类继承自Farmer类和,但不符合hasAVariablePotato,因为没有potato var!所以上面会产生错误:

  

Type' PotatoFarmer'不符合协议&has; aavariablePotato'

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

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

错误现在会消失,因为您对协议符合

根据您的情况,您希望UICollectionViewLayoutUICollectionViewLayoutAttributes单独的子类。要查看如何执行此操作,请查看此处(关于此主题的免费教程): https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest

答案 1 :(得分:0)

斯威夫特并不支持多重继承。 UICollectionViewController和UICollectionViewLayout都是类。不要继承这门课程。您可以使用以下代码

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
    }
}