简体   繁体   中英

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

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 (eg accessing properties only available in 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM