Skip to content

Instantly share code, notes, and snippets.

@stuartjmoore
Last active October 21, 2016 13:08
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stuartjmoore/9552590 to your computer and use it in GitHub Desktop.
Save stuartjmoore/9552590 to your computer and use it in GitHub Desktop.
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