通用IBDesginables UIView扩展

我想为类创建通用扩展,为任何UIView子类添加一些可设计的function,并避免向所有子类添加function。 因此,为UIView添加符合协议SomeProtocol的扩展会很好(它是空的,因为它只是一个标记类的标记,我想要添加function)。 然后在任何UIView子类中添加该协议,我希望这样的function实现如下:

protocol SomeProtocol { //empty } class BCBorderedView : UIView, SomeProtocol { //empty } class BCBorderedSearch: UISearchBar, SomeProtocol { //empty } 

下面我的实现收到错误消息

“尾随’where’子句用于扩展非generics类型’UIView’”

 @IBDesignable extension UIView where Self:SomeProtocol //Error: Trailing 'where' clause for extension of non-generic type 'UIView' { @IBInspectable public var cornerRadius: CGFloat { set (radius) { self.layer.cornerRadius = radius self.layer.masksToBounds = radius > 0 } get { return self.layer.cornerRadius } } @IBInspectable public var borderWidth: CGFloat { set (borderWidth) { self.layer.borderWidth = borderWidth } get { return self.layer.borderWidth } } @IBInspectable public var borderColor:UIColor? { set (color) { self.layer.borderColor = color?.cgColor } get { if let color = self.layer.borderColor { return UIColor(cgColor: color) } else { return nil } } } } 

删除where子句编译和工作,但它为所有UIViews及其子类(基本上所有UI元素)添加了function,这使得IB代理在storyboard中不时崩溃。

有什么想法可以更新这个计划吗?

extension Foo where ……只有在extension Foo where才能使用

  • 通用类或结构
  • 包含一些相关类型的协议
  • 当Self属于特定(对象/引用)类型或符合某种类型约束时,我们使用默认实现扩展的协议。

尾随’where’子句扩展非generics类型’UIView’

上述错误意味着UIView是非generics类类型,因此where子句不能在此处应用。

因此,不必尝试扩展UIView ,您必须使用默认实现扩展SomeProtocol ,以用于Self: UIView

您的扩展应该将function扩展到符合SomeProtocol且类型为UIView所有类型

简而言之,您应该在扩展子句中切换顺序。 所以,

 extension UIView where Self : SomeProtocol 

应该

 extension SomeProtocol where Self: UIView