如何使扩展既有出口(swift 2)
How to make extension both outlet (swift 2)
我为 UITextField 创建了扩展。我需要相同的 UITextView 扩展。如何使此扩展程序可用于所有其他视图?
我的扩展代码:
extension UITextField {
func addTopBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, 0, self.frame.size.width, height)
self.layer.addSublayer(border)
}
func addRightBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(self.frame.size.width - height, 0, height, self.frame.size.height)
self.layer.addSublayer(border)
}
func addBottomBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, self.frame.size.height - height, self.frame.size.width, height)
self.layer.addSublayer(border)
}
func addLeftBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, 0, height, self.frame.size.height)
self.layer.addSublayer(border)
}
}
您应该只为 UIView
创建扩展。
作为其他 类(UITextField
、UITextView
、UILabel
、...)扩展 UIView
,它们都应该具有您的功能。
注意:这要求函数适用于 UIView 且不包含特定操作(例如,访问仅在 UITextView
中可用的属性)。
如果您只想扩展几个 类,您可以定义一个协议并在协议中提供默认实现,然后使用新协议扩展 类。这是您可以在 playground 中 运行 的一个简单示例:
protocol foo {
func bar() -> String;
}
extension foo {
func bar() -> String {
return "bar"
}
}
extension Float: foo {}
extension Int: foo {}
let i = 12
print(i.bar())
let f:Float = 1.0
print (f.bar())
我为 UITextField 创建了扩展。我需要相同的 UITextView 扩展。如何使此扩展程序可用于所有其他视图?
我的扩展代码:
extension UITextField {
func addTopBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, 0, self.frame.size.width, height)
self.layer.addSublayer(border)
}
func addRightBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(self.frame.size.width - height, 0, height, self.frame.size.height)
self.layer.addSublayer(border)
}
func addBottomBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, self.frame.size.height - height, self.frame.size.width, height)
self.layer.addSublayer(border)
}
func addLeftBorderWithColor(color: UIColor, height: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRectMake(0, 0, height, self.frame.size.height)
self.layer.addSublayer(border)
}
}
您应该只为 UIView
创建扩展。
作为其他 类(UITextField
、UITextView
、UILabel
、...)扩展 UIView
,它们都应该具有您的功能。
注意:这要求函数适用于 UIView 且不包含特定操作(例如,访问仅在 UITextView
中可用的属性)。
如果您只想扩展几个 类,您可以定义一个协议并在协议中提供默认实现,然后使用新协议扩展 类。这是您可以在 playground 中 运行 的一个简单示例:
protocol foo {
func bar() -> String;
}
extension foo {
func bar() -> String {
return "bar"
}
}
extension Float: foo {}
extension Int: foo {}
let i = 12
print(i.bar())
let f:Float = 1.0
print (f.bar())