[英]How to make extension both outlet (swift 2)
I created extension for UITextField. 我为UITextField创建了扩展名。 And I need the same extension for UITextView.
而且我需要UITextView的相同扩展名。 How to make this extension available for all other views?
如何使此扩展程序可用于所有其他视图?
My extension code: 我的扩展代码:
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)
}
}
You should only create the extension for UIView
. 您应该只为
UIView
创建扩展。 As the other classes ( UITextField
, UITextView
, UILabel
, ...) extend UIView
, they all should have your functions available. 随着其他类(
UITextField
, UITextView
, UILabel
,...)扩展UIView
,它们都应具有可用的功能。
NOTE : This requires that the functions work for UIView and don't contain specific operations (eg accessing properties only available in UITextView
). 注意 :这要求这些函数适用于UIView,并且不包含特定的操作(例如,访问仅在
UITextView
可用的属性)。
In the case when you want an extension for only a few classes, you could define a protocol and provide default implementations in the protocol, then extend the classes with the new protocol. 如果只想扩展几个类,则可以定义一个协议并在该协议中提供默认实现,然后使用新协议扩展这些类。 Here's a trivial example you can run in 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.