這其實是很早之前(大概從一開始寫 iOS 的時候)就知道不用特別 conforming ,就可以直接實作 UIScrollViewDelegate
的 methods 了,例如:
// Objective-C
@interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
或是
// Swift
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
而不用寫成:
// Objective-C
@interface MyViewController : UIViewController <UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>
或是
// Swift
class MyViewController: UIViewController, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate
以前認為得非常理所當然,所以都沒有去看到底是為什麼。瞭解了之後,就來一篇說明的文章。
這些 protocols 有繼承 UIScrollViewDelegate
Objective-C 和 Swift 的 protocol 可以繼承另外一個 protocol
一般的 protocols ,如 UITableViewDataSource
,都是直接繼承 NSObject 這個 protocol (在 Swift 的話就是繼承 NSObjectProtocol),以下是他們的宣告方式:
// Objective-C
@protocol UITableViewDataSource<NSObject>
或是
// Swift
public protocol UITableViewDataSource : NSObjectProtocol
而以 UITableViewDelegate
和 UICollectionViewDelegate
來說,他們有繼承 UIScrollViewDelegate
,以下則是他們的宣告方式:
// Objective-C
// UITableViewDelegate
@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>
// UICollectionViewDelegate
@protocol UICollectionViewDelegate<NSObject, UIScrollViewDelegate>
或是
// Swift
// UITableViewDelegate
public protocol UITableViewDelegate : UIScrollViewDelegate
// UICollectionViewDelegate
public protocol UICollectionViewDelegate : UIScrollViewDelegate
因此這一類的 protocols 和 UIScrollViewDelegate
有繼承的關係,就可以使用 UIScrollViewDelegate
的所有 methods 了
如果對於本篇有什麼問題和討論,歡迎在下面提出來,謝謝