【发布时间】:2017-06-22 17:09:56
【问题描述】:
我想为类创建通用扩展,以向任何 UIView 子类添加一些可设计的功能,从而避免向所有子类添加功能。因此,为 UIView 添加符合协议 SomeProtocol 的扩展会很好(它是空的,因为它只是一个标记我想要添加功能的类的标签)。然后只需在我希望实现该功能的任何 UIView 子类中添加该协议,如下所示:
protocol SomeProtocol {
//empty
}
class BCBorderedView : UIView, SomeProtocol
{
//empty
}
class BCBorderedSearch: UISearchBar, SomeProtocol
{
//empty
}
我在下面的实现收到错误消息
"用于扩展非泛型类型 'UIView' 的尾随 'where' 子句"
@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 子句可以编译和工作,但它会向所有 UIView 及其子类(基本上所有 UI 元素)添加功能,这会使 IB 代理在情节提要中不时崩溃。
有什么想法可以更新这个计划吗?
【问题讨论】:
标签: ios generics swift3 swift-extensions ibdesignable