Search code examples
swiftswift2swift-extensions

How to make extension both outlet (swift 2)


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)
    }
}

Solution

  • 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).