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

前端 未结 2 534
爱一瞬间的悲伤
爱一瞬间的悲伤 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!

    0 讨论(0)
  • 2021-01-14 18:42

    I don't really get you mean. But you want to set custom "text style" from Interface Builder you can do this. for UILable

    1, Create category UILabel + MyCustomStyle.

    in UILabel + MyCustomStyle.h

    #import <UIKit/UIKit.h>
    
    @interface UILabel (MyCustomStyle)
    
    @property (nonatomic, copy) NSString *mTextStyle;
    
    @end
    

    in UILabel + MyCustomStyle.m

    #import "UILabel+MyCustomStyle.h"
    
    @implementation UILabel (MyCustomStyle)
    
    -(NSString *)mTextStyle {
        return self.text;
    }
    
    -(void)setMTextStyle:(NSString *)txt{
    
            if ([txt isEqualToString:@"h1"]) {
    
            // custom style h1 code
            self.font = ...;
        }else if ([txt isEqualToString:@"h2"]){
    
            // custom style h2 code
            self.font = ...;
        }
        //... more custom style
    }
    

    2, Assign text style in IB

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题