Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creates an NSTextAttachment the takes up the entire width of the line fragment (while maintaining its aspect ratio). Instead of a simple image, any UIView (that has a (CGFloat)heightThatFits method) will work.
//
// WPTextAttachment.h
// ReadArticle
//
// Created by Moore, Stuart on 12/27/13.
// Copyright (c) 2013 The Washington Post. All rights reserved.
//
#import <UIKit/UIKit.h>
@class NativeDownloadable, WPDownloadableItemView;
@interface WPTextAttachment : NSTextAttachment
@property (nonatomic, weak) UIView *view;
@property (nonatomic, assign) CGSize size;
@end
//
// WPTextAttachment.m
// ReadArticle
//
// Created by Moore, Stuart on 12/27/13.
// Copyright (c) 2013 The Washington Post. All rights reserved.
//
#import "WPTextAttachment.h"
#import "WPTextContainer.h"
@implementation WPTextAttachment
- (CGRect)attachmentBoundsForTextContainer:(WPTextContainer*)container
proposedLineFragment:(CGRect)lineFrag
glyphPosition:(CGPoint)position
characterIndex:(NSUInteger)index {
CGFloat width = lineFrag.size.width;
CGSize size = self.size;
CGFloat ratio = (size.height == 0 || isnan(size.height))? 0 : size.width / size.height;
CGFloat height = self.view? self.view.heightThatFits : ((ratio == 0)? 0 : width / ratio);
width = (height == 0)? width = 0 : width;
self.bounds = CGRectMake(0, 0, ceilf(width), ceilf(height));
if(self.view.superview != container.view)
[container.view addSubview:self.view];
CGRect lineRect = lineFrag;
lineRect.size = self.bounds.size;
self.view.frame = CGRectIntegral(lineRect);
return self.bounds;
}
- (UIImage*)imageForBounds:(CGRect)bounds textContainer:(WPTextContainer*)container characterIndex:(NSUInteger)index {
return nil;
}
@end
//
// WPTextContainer.h
// WashPost
//
// Created by Moore, Stuart on 1/16/14.
// Copyright (c) 2014 Washington Post. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface WPTextContainer : NSTextContainer
@property (nonatomic, weak) UITextView *view; // you need to set this up.
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment