Custom Text Views

Attributed Text

Looking at Interface Builder, specifically the attributes inspector of a UILabel, it would seem attributed text is a straight-forward affair.

Drag a label into a storyboard, change it to attributed, done.

I tried this, and while it very well may have been a freak occurrence, I couldn't immediately get it up and running, so I decided to throw together a workaround.

In addition to button and clocks, Paintcode can quickly create custom text with the fonts available in iOS. The text tool opens a pre-populated text box on the canvas.

Using Paintcode's variables feature, I added a parameter for text and fontSize, text and number variables respectively.

Which is then connected to the text box.

Now, text and fontSize are determined by these two variables not only within Paintcode, but the generated code as well. This means that, along with a frame parameter, the drawing code which will eventually be called in app can access text, size, and the size of the text box.

func drawTextLine(#frame: CGrect, text: String, fontSize: CGFloat) {
let context = UIGraphicsGetCurrentContext()

I created a subclass of UIView called TextLineView. With @IBDesignable in the class declaration, the view will render in Interface Builder. And, if you add the @IBInspectable to a couple of choice vars like textForView and sizeForText, those too become available under the Attributes Inspector.

Paintcode's exported stylekit is a bit of a hefty beast for a single function, so you can copy drawTextLine and declare it in the subclass.

And, since drawTextLine is called within drawRect, using the passed in values, the text is rendered live(ish).

@IBDesignable class TextLineView: UIView {

@IBInspectable var textForView: String = "Placeholder"
@IBInspectable var sizeForText: CGFloat = 20.0

	override func drawRect(rect: CGRect) {
    // Drawing code
    drawTextLine(frame: self.bounds, text: textForView, fontSize: sizeForText)

So, now I have a reusable Attributed Text View. I can add a UIView to a storyboard, set its class to TextLineView, and be able to change the font and size from Interface Builder.

I noticed that if I added @IBInspectable variables and switched between the storyboard and the code, they become somewhat baked into the storyboard item; If I deleted them from class, they would still be referenced in Interface Builder. But, Xcode will give multiple warnings, so it's easy to catch.