为添加边框的 UIView 创建子类的步骤是什么?

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

在我目前的项目中,我经常创建一个 UIView 来在视图上放置一个灰色的矩形。我通常先在布局上放置白色视图,然后在 viewDidLoad() 中设置所有边框。现在我决定通过编写一个自动设置视图边框的子类来加快速度,然后将所有这些视图设置为使用该子类。但是我不知道把这段代码放在子类的什么地方:

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

我把它放在 override init() 上吗?我是否需要为 UIView 覆盖 init 的每个版本?或者有更好的方法吗?

谢谢。

PS:如果还有什么方法可以让边框在故事板设计时立即显示(我认为这与drawable有关但我不明白全部),我将不胜感激!

编辑:

从接受的答案中,我得到了这个答案: 基本上是这样的:

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

这里有一个非常详细的答案:

Proper practice for subclassing UIView?

基本上,您应该覆盖:

init?(coder aDecoder: NSCoder)init(frame: CGRect) 以及 awakeFromNib()。只需从设置边框的地方调用另一个函数。

您需要创建 UIView 的子 class 并根据您的需要在此 class 中声明 IBInspectable 属性。

尝试以下链接作为示例:

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

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