iOS归因于字符串 - 最小的例子

tob*_*jim 7 nsattributedstring ios

我最近决定解决我遇到的问题的最佳方法是使用NSAttributedString实例.文档似乎缺乏,至少对新手而言.stackoverflow的答案主要有两种类型:

  1. 阅读文档
  2. 使用AliSoftware最优秀的OHAttributedLabel类.

我真的很喜欢第二个答案.但是我想更好地理解NSAttributedString,所以我在这里提供了最小的(?)组装和显示属性字符串的示例,以防它帮助其他人.

我使用Storyboard和ARC在Xcode(4.5.2)中为iPad创建了一个新的单窗口项目.

AppDelegate没有任何变化.

我创建了一个基于UIView的新类,将其命名为AttributedStringView.对于这个简单的示例,最简单的方法是使用drawAtPoint:方法将属性字符串放在屏幕上,这需要一个有效的图形上下文,并且在UIView子类的drawRect:方法中最容易获得.

这是完整的ViewController.m(没有对头文件进行任何更改):

#import "ViewController.h"
#import "AttributedStringView.h"

@interface ViewController ()

@property (strong, nonatomic) AttributedStringView *asView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.asView];
}

- (AttributedStringView *)asView
{
    if ( ! _asView ) {
        _asView = [[AttributedStringView alloc] initWithFrame:CGRectMake(10, 100, 748, 500)];
        [_asView setBackgroundColor:[UIColor yellowColor]]; // for visual assistance
    }
    return _asView;
}

@end
Run Code Online (Sandbox Code Playgroud)

这里是完整的AttributedStringView.m(没有对头文件进行任何更改):

#import "AttributedStringView.h"

@interface AttributedStringView ()

@property (strong, nonatomic) NSMutableAttributedString *as;

@end
@implementation AttributedStringView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
if (self) {
    NSString *text = @"A game of Pinochle is about to start.";
    //                 0123456789012345678901234567890123456
    //                 0         1         2         3
    _as = [[NSMutableAttributedString alloc] initWithString:text];
        [self.as addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:36] range:NSMakeRange(0, 10)];
        [self.as addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:36] range:NSMakeRange(10, 8)];
        [self.as addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:36] range:NSMakeRange(18, 19)];

        if ([self.as size].width > frame.size.width) {
            NSLog(@"Your rectangle isn't big enough.");
            // You might want to reduce the font size, or wrap the text or increase the frame or.....
        }
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    [self.as drawAtPoint:CGPointMake(0, 100)];
}

@end
Run Code Online (Sandbox Code Playgroud)