3

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;
  }
}
Community
  • 1
  • 1
Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124

2 Answers2

1

You need to create subclass of UIView and declare IBInspectable properties as per your needs in this class .

Try below links as example :

http://nshipster.com/ibinspectable-ibdesignable/

https://www.captechconsulting.com/blogs/ibdesignables-in-xcode-6-and-ios-8

KKRocks
  • 8,222
  • 1
  • 18
  • 84
0

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.

Community
  • 1
  • 1
Moriya
  • 7,750
  • 3
  • 35
  • 53
  • Thanks! The answer that really become my solution from your link is this: http://stackoverflow.com/a/33721647/3003927 which put a `didLoad()` function call on both init frame and init coder. – Chen Li Yong Oct 17 '16 at 09:17