为什么我需要覆盖甚至没有在超类中实现的方法?

时间:2018-01-25 11:54:33

标签: ios swift uicollectionview

我有一个简单的FriendsController类,它是UICollectionViewController的子类,所以当我实现UICollectionViewDataSource协议所需的函数时,为什么我需要在func声明前面放置重写关键字,甚至在UICollectionViewController父类中都没有实现。

class FriendsController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
  fileprivate let cellId = "cellId"
  var messages: [Message]?


   override func viewDidLoad() {

    super.viewDidLoad()
    navigationItem.title = "Recent"
    collectionView?.backgroundColor = UIColor.white
    collectionView?.register(MessageCell.self, forCellWithReuseIdentifier: cellId)
    collectionView?.alwaysBounceVertical = true
    setupData()

   }


 override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if let count = messages?.count {
        return count
    }
     return 0
}

我已经看到UIViewCollectionController没有实现协议所需的功能:

  open class UICollectionViewController : UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {


public init(collectionViewLayout layout: UICollectionViewLayout)

public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)

public init?(coder aDecoder: NSCoder)


open var collectionView: UICollectionView?


// Defaults to YES, and if YES, any selection is cleared in viewWillAppear:
// This property has no effect if the useLayoutToLayoutNavigationTransitions property is set to YES
open var clearsSelectionOnViewWillAppear: Bool


// Set to YES before pushing a a UICollectionViewController onto a
// UINavigationController. The top view controller of the navigation controller
// must be a UICollectionViewController that was pushed with this property set
// to NO. This property should NOT be changed on a UICollectionViewController that
// has already been pushed onto a UINavigationController.
@available(iOS 7.0, *)
open var useLayoutToLayoutNavigationTransitions: Bool


// The layout object is needed when defining interactive layout to layout transitions.
@available(iOS 7.0, *)
open var collectionViewLayout: UICollectionViewLayout { get }


// Defaults to YES, and if YES, a system standard reordering gesture is used to drive collection view reordering
@available(iOS 9.0, *)
open var installsStandardGestureForInteractiveMovement: Bool
  }

2 个答案:

答案 0 :(得分:2)

UICollectionViewController符合UICollectionViewDataSourceUICollectionViewDelegate,因此必须实施这些协议所需的方法,包括numberOfItemsIn:,这就是您需要使用{{1}的原因}}

答案 1 :(得分:0)

它不是一个超类,而是一个协议,你的类需要遵守它。