Search code examples
iosswiftuiviewsubclassing

What is the steps to create a subclass for UIView that adds border?


In my current project, I often create a UIView to put a grey rectangle on the view. I usually put white views first on the layout, and then set all of the border in the viewDidLoad(). Now I decided that I want to speed things up by writing a subclass that will automatically set the border of the view, and then set all those views to use that subclass. But I don't know where to put this code on the subclass:

self.layer.borderWidth = 2;
self.layer.borderColor = UIColor.grayColor().CGColor;

Do I put it on override init()? Do I need to override every version of init for the UIView? Or is there a better way to do this?

Thanks.

PS: if there's also any way to make that the border can be immediately shown on the storyboard design time (I think it has something to do with drawable but I don't understand at all about it), I'll be very grateful!

EDIT:

From the accepted answer, I get this answer: https://stackoverflow.com/a/33721647/3003927 which basically like this:

import UIKit

class MyView: UIView {
  override init(frame: CGRect) {
      super.init(frame: frame)
      didLoad()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    didLoad()
  }

  convenience init() {
    self.init(frame: CGRectZero)
  }

  func didLoad() {
    //Place your initialization code here
    self.layer.borderWidth = 2;
    self.layer.borderColor = UIColor.grayColor().CGColor;
  }
}

Solution

  • There's a pretty detailed answer here:

    Proper practice for subclassing UIView?

    Basically, you should override:

    init?(coder aDecoder: NSCoder) and init(frame: CGRect) as well as awakeFromNib(). Just call another function from there where you set the border.