Christopher Francisco
Christopher Francisco

Reputation: 16278

iOS adding design-time text on storyboard

Is it possible to set a design-time text for UILabel (or image if using UIImageView) on iOS 8? if so, how to?

Basically what I need is not to empty all of my labels before compiling so that it doesn't show dummy data before loading from the network the actual data. An algorithm to programatically clear all outlets isn't really a good solution as it is unnecessary code.

Upvotes: 0

Views: 742

Answers (1)

Will M.
Will M.

Reputation: 1854

You could try subclassing the classes you want to have design-time attributes. Here is an example of that for UILabel:

import UIKit

class UIPrototypeLabel: UILabel {
    @IBInspectable var isPrototype: Bool = false

    override func awakeFromNib() {
    if (isPrototype) {
        self.text = "test"
    }
}

Then, in IB, you will see isPrototype, and you can set it to true or false.

You can also change the default from false to true in the isPrototype:Bool = false line if you want. You can also change what happens if isPrototype is true. I had it make the text "test" so I could see feedback when testing this out, so you could change it to nil or "" or whatever.

You can also just eschew the isPrototype bool and have this class always reset the text. I just thought the IBInspectable attribute was cool, but if you just want this class to always clear the label text then you would just delete the bool and the check and just self.text=nil every time.

The con to this approach is you need to make all of your labels UIPrototypeLabel to get this functionality.

enter image description here

There is a second, scarier approach, that will add this functionality to all of your UILabels, and that is extending UILabel.

import ObjectiveC
import UIKit
// Declare a global var to produce a unique address as the assoc object handle
var AssociatedObjectHandle: UInt8 = 0

extension UILabel {
    @IBInspectable var isPrototype:Bool {
        get {
            var optionalObject:AnyObject? = objc_getAssociatedObject(self, &AssociatedObjectHandle)

            if let object:AnyObject = optionalObject {
                return object as! Bool
            } else {
                return false // default value when uninitialized
            }
        }
        set {
            objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
        }
    }

    public override func awakeFromNib() {
        if (isPrototype) {
            self.text = "test"
        }
    }
}

credit to Is there a way to set associated objects in Swift? for some of that code

Upvotes: 2

Related Questions