Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing "text styles" in Interface Builder and/or Storyboards

In one of my apps I have a styles document with methods for different text styles, for example:

+(UIFont*)h1{
    return [UIFont fontWithName:@"Helvetica" size:48.0];
}

Then, in the viewDidLoad methods of each my view controllers, I set the text styles programmatically. It's been a really great way to keep styles across the app consistent and easy to tweak.

Here's my question: is there any way to have the XIB files/Storyboards reflect these text styles? If not, is there any way to implement similar functionality (i.e., have all the styles defined in one place, and have the XIB/Storyboard elements pull from there)? Thanks for reading.

EDIT:

To clarify, here's the desired end-result:

  1. Define some constant text styles like h1, h2, p somewhere in the project. Each text style has its own font, font size, colour, and so on.
  2. Be able to set the style of UILabels in my various views to any of these text styles. This could be done in code, in Interface Builder (e.g., in User Defined Runtime Attributes as Luan suggested), or wherever.
  3. Be able to see the styles applied to each UILabel in Interface Builder / Storyboard without having to run the app every time.
like image 330
Rogare Avatar asked Sep 18 '25 19:09

Rogare


1 Answers

OK, so it turns out this is possible to do! Here's how:

  1. Add a styles class, where you can put all your style info in one place:

    import UIKit
    
    class MyStyles: NSObject {
      static func fontForStyle(style:String)->UIFont{
        switch style{
        case "p":
          return UIFont.systemFontOfSize(18);
        case "h1":
            return UIFont.boldSystemFontOfSize(36);
        case "h2":
            return UIFont.boldSystemFontOfSize(24);
        default:
            return MyStyle.fontForStyle("p");
        }
      }
    }
    
  2. Make a subclass of any objects you'd like to implement the styles, say UILabel, and enter the following code:

    import UIKit
    
    @IBDesignable class MyLabel: UILabel {
      @IBInspectable var style:String="p"{
        didSet{self.font=MyStyle.fontForStyle(style)} 
      }
    }
    
  3. Add a UILabel to your view in Interface Builder and set its class to MyLabel. Then in the Attributes Inspector, you'll see a Style field where you can type h1, h2 or whatever, and the label's font will update right away. Want to change all your h1 labels to have a size of 48? Just update MyStyles and you'll see the changes in your XIBs/Storyboards right away.

This is going to be a huge time-saver, I hope some of you find it useful too!

like image 169
Rogare Avatar answered Sep 20 '25 10:09

Rogare