Tuesday, March 1, 2016

Draw a red border around your UIView for debugging purposes

A lot of the times, you're dealing with UITextViews and UITextFields that have the same

A lot of the times, you're dealing with UITextViews and UITextFields that have the same white background and border as the superviews they sit on top of. It's helpful every now and then to make sure they're obeying the constraints you want them to have. In my case, I made a self-contained UITextView that has a placeholder functionality but the textView wasn't constraining to the size of its container view.

DOH!

image

Ahh... needed better constraints:

func applyConstraintsToTextView() {

    if let validTextView = self.placeholderTextView {
        let viewsDictionary = ["textView":validTextView]
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[textView]|", options: [], metrics: nil, views: viewsDictionary))
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[textView]|", options: [], metrics: nil, views: viewsDictionary))
        setNeedsLayout()
    }
}

Now add this extension to UIView

extension UIView {

func drawRedBorder() {
    self.layer.borderColor = UIColor.redColor().CGColor
    self.layer.borderWidth = 1.0;
    }
}

simply call it on the view (any UIView subclass) and see where the borders are landing.

validTextView.drawRedBorder()

Much better...

image