Example of NSTextContainer with non regular shape? - ios

Hi I'm working with the new TextKit API for iOS7 and I'm trying to produce a UITextView with an irregular shape. So far I have in a view controller:
-(void) loadView
{
self.view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,548)];
NSTextStorage *textStorage = [[NSTextStorage alloc] init];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager: layoutManager];
BaseTextContainer *textContainer = [[BaseTextContainer alloc] initWithSize:CGSizeMake(100, 100)];
[layoutManager addTextContainer: textContainer];
BaseTextView *textView = [[BaseTextView alloc] initWithFrame:CGRectMake(110,124, 100, 100) textContainer:textContainer];
textView.backgroundColor = [UIColor blueColor];
textView.editable = YES;
[self.view addSubview:textView];
}
Then in my subclassed NSTextContainer, I want to have a mutablePath drawn as the shape of the text container, but not sure how to accomplish this. I have:
- (BOOL) isSimpleRectangularTextContainer
{
return NO;
}
- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
NSLog(#"TEST");
CGContextRef context = ctx;
CGSize layerSize = layer.frame.size;
CGAffineTransform transform = CGAffineTransformMakeScale(layerSize.width / self.initialSize.width, layerSize.height / self.initialSize.height);
CGMutablePathRef newGraphicMutablePath = CGPathCreateMutableCopyByTransformingPath(self.mutablePath, &transform);
CGContextAddPath(context, newGraphicMutablePath);
CGPathRelease(newGraphicMutablePath);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextDrawPath(context, kCGPathFill);
}
Just a bit confused about how to get this to work. I cannot find an example anywhere of an NSTextContainer with an irregular shape.

There is no need for all that code constructing the Text Kit stack, as you are not modifying the architecture of the stack. Just start with a normal UITextView - let's say it's self.textView - and then assign one or more UIBezierPath objects to its exclusion paths:
self.tv.textContainer.exclusionPaths = myArrayOfBezierPaths;
These paths are exclusion paths, so for an ellipse you will want to make four paths, each one describing a corner of the text container.
Alternatively, you can build the Text Kit stack yourself so as to insert your own text container subclass, and modify where the text is allowed to go by overriding lineFragmentForProposedRect:, perhaps similar to what I do here: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch10p537exclusionPath2/ch23p813textKitShapes/MyTextContainer.swift
Some experiments:

Related

UITextView, NSAttributedString and custom attributes

I have searched a lot on Stack Overflow but I couldn't find a solution. Perhaps I just misinterpreted some answers.
I have created a UITextView and I am using NSAttributedStrings to work with the UITextView which is just fine.
Now, after adding a custom attribute, I am stuck.
Where can I hook in to render my custom attribute within the UITextView? Is there a delegate method, or will I have to create my own UITextView and overwrite a method?
You can custom NSLayoutManager, and implement it's -drawGlyphsForGlyphRange:atPoint: method.
For example, you want a custom background with a corner radius
textView init:
NSTextStorage *textStorage = [NSTextStorage new];
CustomLayoutManager *layoutManager = [[CustomLayoutManager alloc] init];
CGSize containerSize = CGSizeMake(self.view.bounds.size.width, CGFLOAT_MAX);
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:containerSize];
textContainer.widthTracksTextView = YES;
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
self.textView = [[UITextView alloc] initWithFrame:yourFrame textContainer:textContainer];
And apply your custom attribute:
NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:#"SampleText"];
[mAttrStr addAttribute:YourCustomAttributeName value:[UIColor redColor] range:NSMakeRange(0, mAttrStr.length)]; //for example, you want a custom background with a corner radius
[self.textView.textStorage appendAttributedString:mAttrStr];
In CustomLayoutManager.m
-(void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origin {
NSRange range = [self characterRangeForGlyphRange:glyphsToShow
actualGlyphRange:NULL];
//enumerate custom attribute in the range
[self.textStorage enumerateAttribute:YourCustomAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value) {
UIColor *color = value; //the color set above
NSRange glyphRange = [self glyphRangeForCharacterRange:range
actualCharacterRange:NULL];
NSTextContainer *container = [self textContainerForGlyphAtIndex:glyphRange.location
effectiveRange:NULL];
//draw background
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, origin.x, origin.y);
[color setFill];
CGRect rect = [self boundingRectForGlyphRange:glyphRange inTextContainer:container];
//UIBezierPath with rounded
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:100];
[path fill];
CGContextRestoreGState(context);
//end draw
[super drawGlyphsForGlyphRange:range atPoint:origin];
}
else {
[super drawGlyphsForGlyphRange:range atPoint:origin];
}
}];
}
Now the 'SampleText' has a red rounded background.
Please refer this simple code snippet to set attributed string to a textview
let attributedString = NSMutableAttributedString(string:"Test string to add attributes")
attributedString.addAttributes([NSForegroundColorAttributeName:UIColor.greenColor()], range: NSMakeRange(0, attributedString.string.characters.count))
textView.attributedText = attributedString
For Objective-C
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:#"Test string to add attributes"];
[attributedString addAttributes:#{NSForegroundColorAttributeName:[UIColor greenColor]} range:NSMakeRange(0, attributedString.string.length)];
textView.attributedText = attributedString;
Hope this helps.
If you want apply particular attributes for particular textView rather then string then you should subclass UITextView and make custom initmethod or some method that return UITextView object with specified attribute!! You can pass custom attributes as parameter in method also if attributes are change i mean not fix. and if attribute will remain same implicitly then set attributes in that class by default.

multiple punch-out style mask?

I've done simple CALayer masks before but I think I'm getting confused on what they do. I'm trying to have a punch out effect with several (2) views.
Here's what I have so far. I'm looking to have a white square with punched out label and image (so you can see the brown background through it. Where am I going wrong?
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor brownColor];
self.viewToPunch = [[UIView alloc] initWithFrame:CGRectZero];
[self.view addSubview:self.viewToPunch];
self.viewToPunch.backgroundColor = [UIColor whiteColor];
self.punchLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.punchLabel.textColor = [UIColor blackColor];
self.punchLabel.font = [UIFont boldSystemFontOfSize:20.0];
self.punchLabel.text = #"punch";
self.punchLabel.textAlignment = NSTextAlignmentCenter;
self.punchImage = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"plus"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
[self.punchImage setContentMode:UIViewContentModeCenter];
self.viewsToPunch = #[self.punchLabel,self.punchImage];
[self punch:self.viewToPunch withUIViews:self.viewsToPunch];
}
- (void)punch:(UIView *) viewToPunch withUIViews:(NSArray *)viewsToPunch
{
CALayer *punchMask = [CALayer layer];
punchMask.frame = viewToPunch.frame;
NSMutableArray *sublayers = [[NSMutableArray alloc] init];
for (UIView *views in viewsToPunch){
[sublayers addObject:views.layer];
}
punchMask.sublayers = sublayers;
punchMask.masksToBounds = YES;
viewToPunch.layer.mask = punchMask;
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
self.viewToPunch.frame = CGRectMake(50, 50, 100, 100);
self.punchLabel.frame = CGRectMake(0, 0, 100, 100);
self.punchImage.frame = CGRectMake(0, 0, self.viewToPunch.frame.size.width, 40.);
[self punch:self.viewToPunch withUIViews:self.viewsToPunch];
}
So not only do the frames seem to be off, it seems to be the opposite of a punch out. How do I invert the mask and fix up the frames?
Thanks a lot for any help! I put it in a method punch:withUIViews: so I can hopefully reuse it in other areas.
When you apply a mask to a CALayer, it only gets drawn in the parts where the mask is not transparent. But you're simply applying an empty (transparent) mask, with the wrong coordinates (which is why your view isn't completely transparent: the mask isn't covering the view completely; it should be punchMask.frame = viewToPunch.bounds;)
You might want to look into CAShapeLayer and assign it a path. Use that as mask layer.
For example, see CAShapeLayer mask view or Getting Creative with CALayer Masks (cached blog post).
I tried to combine mask of CAGradationLayer and CAShapeLayer, and It is possible.
https://stackoverflow.com/a/32220792/3276863

textkit custom text attribute draws big rect when it spans multiple lines

I am basically creating a custom attribute to draw a rounded rectangle in my text subclassing NSLayoutManager with drawGlyphsForGlyphRange method below. Below works like a charm with ranges that spans one line. However, when the range of text spans in two lines, I am getting a big rectangle which draws the attribute along those two lines. I think I should be using a different approach here, I tried nsbackgroundattribute to draw the highlight but unfortunately I cannot make the highlight rounded rect using that.
I would appreciate any directions.
-(void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origin {
NSTextStorage *textStorage = self.textStorage;
NSRange glyphRange = glyphsToShow;
while (glyphRange.length > 0) {
NSRange charRange = [self characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL], attributeCharRange, attributeGlyphRange;
id attribute = [textStorage attribute:IKSpecialHighlightAttributeName atIndex:charRange.location longestEffectiveRange:&attributeCharRange inRange:charRange];
attributeGlyphRange = [self glyphRangeForCharacterRange:attributeCharRange actualCharacterRange:NULL];
attributeGlyphRange = NSIntersectionRange(attributeGlyphRange, glyphRange);
if( attribute != nil ) {
NSTextContainer *textContainer = self.textContainers[0];
CGRect boundingRect = [self boundingRectForGlyphRange:attributeGlyphRange inTextContainer:textContainer];
[[UIColor colorWithRed:221.0/255.0 green:255.0/255.0 blue:0.0/255.0 alpha:1] setFill]; // set rounded rect's bg color
boundingRect.origin.x += origin.x-3.0;
boundingRect.origin.y += origin.y+3.0;
boundingRect.size.width += 6.0;
UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:boundingRect cornerRadius: 3.0];
[roundedRect fillWithBlendMode: kCGBlendModeNormal alpha:1.0f];
[super drawGlyphsForGlyphRange:attributeGlyphRange atPoint:origin];
}
else {
[super drawGlyphsForGlyphRange:glyphsToShow atPoint:origin];
}
glyphRange.length = NSMaxRange(glyphRange) - NSMaxRange(attributeGlyphRange);
glyphRange.location = NSMaxRange(attributeGlyphRange);
}
}

Adding exclusion paths to multiple text views

I'm trying to add multiple exclusion paths to a series of UITextViews laid out successively in a UIScrollView, like so:
while (lastRenderedGlyph < self.manager.numberOfGlyphs) {
CGRect textViewFrame = CGRectMake(currentXOffset, 10,
width / 2,
height - 20);
CGSize columnSize = CGSizeMake(CGRectGetWidth(textViewFrame) - 20,
CGRectGetHeight(textViewFrame) - 10);
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:columnSize];
[self.manager addTextContainer:textContainer];
UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame
textContainer:textContainer];
textView.scrollEnabled = NO;
textView.editable = NO;
textView.dataDetectorTypes = UIDataDetectorTypeAll;
textView.delegate = self;
textView.selectable = YES;
UIImageView *goat = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"goat"]];
[goat setContentMode:UIViewContentModeScaleAspectFit];
goat.frame = CGRectMake(0.0, 0.0, 50.0, 50.0);
[textView addSubview:goat];
[self.scrollView addSubview:textView];
textView.textContainer.exclusionPaths = #[[UIBezierPath bezierPathWithRect:CGRectMake(0.0, 0.0, 50.0, 50.0)]];
currentXOffset += CGRectGetWidth(textViewFrame);
lastRenderedGlyph = NSMaxRange([self.manager glyphRangeForTextContainer:textContainer]);
}
However, this causes the app to freeze up, and I've traced the issue to the setting of the exclusion path on each NSTextContainer. For example, if I set no exclusion paths, it works fine. Importantly, if I only set the exclusion path on the first NSTextContainer, then everything works just fine - but anything above one, and the app freezes. What am I doing wrong, or is this a bug?
I guess in retrospect this is obvious, but the solution I arrived at is to add exclusion paths to each new NSTextContainer right after you allocate the container but before doing anything else. i.e.
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:columnSize];
textContainer.exclusionPaths = #[exclusionPath];
[manager addTextContainer: textContainer];
rather than:
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:columnSize];
[manager addTextContainer: textContainer];
textContainer.exclusionPaths = #[exclusionPath];
which causes the app to become unresponsive.
Simple when you know how. This only applies to multi-column, multi-page layouts where you're creating multiple text containers and views and breaking up the glyphs to fit properly. If you're only adding one exclusion path to one view, seems like you can add the exclusion path anywhere.
This is Very easy and helpful thing for ImageWrapping in RichText. but One should keep thing in Mind. a day ago I tried this one and found same code working differently for iOS 7.0 and iOS 7.1
The Blinking Cursor of TextView appears at different place until there is no text in UITextView.
I wrote this code.
UIBezierPath* exclusionPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 38, 21)];
_txtViewMessage.textContainer.exclusionPaths = #[exclusionPath];
and Found Following result in iOS 7.1 and iOS 7.0

How can I access the standard viewForHeaderInSection for a tableView?

I've got an indexed UITableView with individual sections. I would like to use a different background color for the header views in each section. I know I can completely roll my own view by implementing tableView:viewForHeaderInSection: (for example, see question # 2898361), but that seems to be "too much work" to me - the standard view looks fine, I would just have to change its background color.
But how do I access this standard view? I can't use [super tableView:viewForHeaderInSection:] because this is a question of implementing a protocol and not an issue of inheritance. Any other way I can get the standard view?
I'm almost certain you can't do this easily. I used one of my tech support request on my dev account recently asking about altering the background and borders of UITableView sections. The apple engineer told me that this really wasn't an easy thing to do, and even if you managed to do it, you would probably affect performance. He also pointed me to cocoawithlove and an article about editing uitableviews:
http://cocoawithlove.com/2009/08/adding-shadow-effects-to-uitableview.html
Really, creating your own header isn't that much effort. Below is some code I pulled out of one of my projects - it was commented out, so might not work straight away - but you can get the idea:
- (CAGradientLayer *) greyGradient {
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.startPoint = CGPointMake(0.5, 0.0);
gradient.endPoint = CGPointMake(0.5, 1.0);
UIColor *color1 = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0];
UIColor *color2 = [UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0];
[gradient setColors:[NSArray arrayWithObjects:(id)color1.CGColor, (id)color2.CGColor, nil]];
return gradient;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGFloat width = CGRectGetWidth(tableView.bounds);
CGFloat height = [self tableView:tableView heightForHeaderInSection:section];
UIView *container = [[[UIView alloc] initWithFrame:CGRectMake(0,0,width,height)] autorelease];
container.layer.borderColor = [UIColor grayColor].CGColor;
container.layer.borderWidth = 1.0f;
CAGradientLayer *gradient = [self greyGradient];
gradient.frame = container.bounds;
[container.layer addSublayer:gradient];
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(12,0,width,height)] autorelease];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.font= [UIFont boldSystemFontOfSize:19.0f];
headerLabel.shadowOffset = CGSizeMake(1, 1);
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor darkGrayColor];
NSString *title = [self tableView:tableView titleForHeaderInSection:section];
headerLabel.text = title;
return container;
}
Make sure to
#import <QuartzCore/QuartzCore.h>
By the way... this isn't supposed to mimic the look of the standard headers - its just an example. But I'm sure with a bit of trial and error you could alter this to mimic the standard ones and then change the colors slightly.
Although the other answers correctly point out you cannot access the default view to make simple modifications to it, if you have nothing to customize for a particular section header, you can return nil from tableView:viewForHeaderInSection: and the table view will use the default view.
This is helpful if you only need to customize some of your headers.
For whatever reason this is undocumented.
There is one problem with #bandejapalsa solution: the previous cell's separator is still visible with this implementation where as it is not on the default iOS sectionHeaderView. The solution I found was to use a CALayer and offset it by 1 pix. The image needs to be 1pix taller than the view frame itself.
// Create the view for the header
CGRect aFrame =CGRectMake(0, 0, tableView.contentSize.width, IMIUICustomisation.sectionHeaderViewHeight);
UIView * aView = [[UIView alloc] initWithFrame:aFrame];
aView.backgroundColor = UIColor.clearColor;
// Create a stretchable image for the background that emulates the default gradient, only in green
UIImage *viewBackgroundImage = [[UIImage imageNamed:#"greenheader.png"] stretchableImageWithLeftCapWidth:12 topCapHeight:0];
// Cannot set this image directly as the background of the cell because
// the background needs to be offset by 1pix at the top to cover the previous cell border (Alex Deplov's requirement ^_^)
CALayer *backgroungLayer = [CALayer layer];
backgroungLayer.frame = CGRectMake(0, -1, tableView.contentSize.width, IMIUICustomisation.sectionHeaderViewHeight+1);
backgroungLayer.contents = (id) viewBackgroundImage.CGImage;
backgroungLayer.masksToBounds = NO;
backgroungLayer.opacity = 0.9;
[aView.layer addSublayer:backgroungLayer];
// Take care of the section title now
UILabel *aTitle = [[UILabel alloc] initWithFrame: CGRectMake(10, 0, aView.bounds.size.width-10, aView.bounds.size.height)];
aTitle.text = [delegate tableView:tableView titleForHeaderInSection:section];
aTitle.backgroundColor = UIColor.clearColor;
aTitle.font = [UIFont boldSystemFontOfSize:18];
aTitle.textColor = UIColor.whiteColor;
// Text shadow
aTitle.layer.shadowOffset = CGSizeMake(0, 1);
aTitle.layer.shadowRadius = .2;
aTitle.layer.masksToBounds = NO;
aTitle.layer.shadowOpacity = 0.5;
aTitle.layer.shadowColor = IMIUICustomisation.selectedElementTextShadowColor.CGColor;
[aView addSubview:aTitle];
return aView;

Resources