0

I created extension for UITextField. And I need the same extension for 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)
    }
}
mixel
  • 25,177
  • 13
  • 126
  • 165
Clever
  • 401
  • 1
  • 6
  • 17
  • 1
    Why not just making extension to `UIView`? As the other classes (`UITextField`, `UITextView`, `UILabel`, ...) extend `UIView`, they all should have it. – mad_manny Dec 03 '15 at 12:08
  • @mad_manny, you are right. it worked perfect. thanks man – Clever Dec 03 '15 at 12:17

2 Answers2

1

You should only create the extension for UIView. As the other classes (UITextField, UITextView, UILabel, ...) extend UIView, they all should have your functions available.

NOTE: This requires that the functions work for UIView and don't contain specific operations (e.g. accessing properties only available in UITextView).

mixel
  • 25,177
  • 13
  • 126
  • 165
mad_manny
  • 1,081
  • 16
  • 28
1

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())
farhadf
  • 1,918
  • 3
  • 19
  • 27