title: Adding a subview to a UIButton with Auto Layout
body: <p>I have created a subclass of <code>UIButton</code>. This subclass (<code>BubbleBtn</code>) is responsible for adding a <code>UIView</code> to the button.</p>
  
  <p>The view that gets added should be 6 pts from the top, left, and right while spanning half the height of the parent button.</p>
  
  <p>Code:</p>
  
  <pre><code>class BubbleBtn: UIButton {
      override init(frame: CGRect) {
          super.init(frame: frame)
          addBubbleView()
      }
      required init?(coder aDecoder: NSCoder) {
          super.init(coder: aDecoder)
          addBubbleView()
      }
      func addBubbleView() {
          setNeedsLayout()
          layoutIfNeeded()
          let bubbleBuffer:CGFloat = 6
          let bubble = UIView(frame: CGRect(x: bubbleBuffer, y: bubbleBuffer, width: self.frame.width - (bubbleBuffer * 2), height: (self.frame.height / 2)))
          bubble.isUserInteractionEnabled = false
          bubble.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)
          bubble.layer.cornerRadius = 10
          bubble.layer.zPosition = -1
          self.addSubview(bubble)
      }
  }
  </code></pre>
  
  <p>The problem is, the width and the height of the <code>UIView</code> that gets added is not the correct size; both the width and height fall to short on larger buttons. </p>
  
  <p>How do I add the UIView to the buttons so that the bubble view renders in the proper size?</p>
  
  <p>Screenshot posted below:</p>
  
  <p><a href="https://i.stack.imgur.com/wd2rG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wd2rG.png" alt="Autolayout problem with subclass button"></a></p>