In one of my apps I have a styles document with methods for different text styles, for example:
+(UIFont*)h1{
return [UIFont fontWithName:@\"Helvetica\"
-
OK, so it turns out this is possible to do! Here's how:
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");
}
}
}
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)}
}
}
- 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)
-
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)
- 热议问题