Accessing “text styles” in Interface Builder and/or Storyboards

前端 未结 2 533
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 18:15

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

+(UIFont*)h1{
    return [UIFont fontWithName:@\"Helvetica\"          


        
2条回答
  •  鱼传尺愫
    2021-01-14 18:31

    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!

提交回复
热议问题