IOS-bound strings - smallest example

I recently decided that the best solution to the problem was to use instances of NSAttributedString. The documentation seems inadequate, at least for beginners. The answers to stackoverflow were mainly of two types:

I really like the second answer. But I wanted to better understand NSAttributedString, so I provide here the smallest (?) Example of assembling and displaying an attribute string in case it helps others.

I created a new single-window project in Xcode (4.5.2) for iPad using Storiesboards and ARC.

There are no changes to AppDelegate.

I created a new class based on UIView, calling it AttributedStringView. For this simple example, the easiest way is to bind the attribute string on the screen using the drawAtPoint: method, which requires a valid graphics context and which is most easily accessible in the drawRect: method of the UIView subclass.

Here the ViewController.m is completely (no changes to the header file have been made):

#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 

And here AttributedStringView.m is completely (no changes have been made to the header file):

 #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 
+7
source share

All Articles