'required' initializer 'init(coder:)' must be provided by subclass of 'UIView'

/ Mac / 没有评论 / 1706浏览

'required' initializer 'init(coder:)' must be provided by subclass of 'UIView'

在自定义的UIView中使用UICollectionViewFlowLayout()创建了flowLayout然后就出现了如下提示: 'required' initializer 'init(coder:)' must be provided by subclass of 'UIView'

解决方案:

xcode 提示让强制实现如下方法:

required init?(coder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}
分析:
  1. 这是NSCoding协议定义的,是必要构造器(Reguired),当没有定义任何指定构造器(Designated)的时候,父类的必要构造器会自动继承,但是如果我们在子类中定义的指定构造器,就要必须要实现必要构造器,而在子类中只定义了便利构造器(Convenience),则必要构造器会自动继承。
  2. UICollectionViewFlowLayout 的那个无参的构造器是从 UIKit 里面迁移过来的,也就是说这个无参的构造器实际上就是 Objective-C 的 UICollectionViewFlowLayout 的无参构造方法,因为UIKit是OC写的,是Objective-C bridge过来的。
上边代码OC版本:
NSException *exception = [NSException exceptionWithName:@"HotTeaException" reason:@"The tea is too hot" userInfo:nil];
@throw exception;