1

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

2 回答 2

3

超出我的评论。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隐式解包的变量(不是 let 常量) 。像这样:

class PotatoFarmer: Farmer, hasAVariablePotato {

}

上面的PotatoFarmer类继承自一个Farmer类,但不符合hasAVariablePotato因为没有potatovar!所以上面会产生错误:

类型“PotatoFarmer”不符合协议“hasAVariablePotato”

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

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

该错误现在将消失,因为您已遵守协议。

对于您的情况,您希望创建单独的子UICollectionViewLayoutUICollectionViewLayoutAttributes。要查看如何执行此检查(关于该主题的免费教程): https ://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest

于 2016-06-26T17:23:04.613 回答
0

Swift 不支持多重继承。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
    }
}
于 2017-10-20T10:48:59.013 回答