Manjeet Singh
Manjeet Singh

Reputation: 77

Swift Generic methods for UIView subclasses

I want to create a generic method for all controls like UIButton, UILabel, UIView, UITextView, to draw underline for every control.

Is it possible to write such a method for the above classes?

Upvotes: -1

Views: 604

Answers (2)

AnderCover
AnderCover

Reputation: 2661

If you really want to use Swift Generics, you could write something like :

func addUnderline<V>(inView view: V, withHeight height: CGFloat, andColor color: UIColor) where V: UIView {
    let underlineHeight: CGFloat = height
    let underlineView = UIView(frame: CGRect(x: 0, y: view.frame.height - underlineHeight, width: view.frame.width, height: underlineHeight))
    underlineView.backgroundColor = color
    view.addSubview(underlineView)
  }

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100533

Since all elements inherit from UIView , you can try

extension UIView {
 func addUnderline() {
   // create underline view add it with addSubview
 }
}

you can call it from any element

UIButton().addUnderline()
UILabel().addUnderline()

and so on

Upvotes: 2

Related Questions