ASTextNode doesn't render NSAttributedString properly when style.alignment = NSTextAlignmentCenter;
See:

The red is the background color of the ASTextNode
Can you please provide the sample code you used to produce this?
.h
#import "ASDisplayNode.h"
#import <AsyncDisplayKit/ASDisplayNode+Subclasses.h>
#import <ASTextNode.h>
@interface DanceStyleBadge : ASDisplayNode
- (instancetype)initWithDanceStyle:(NSString *)danceStyle;
@property (strong, nonatomic) ASTextNode *danceStyleText;
.m
#import "DanceStyleBadge.h"
@implementation DanceStyleBadge
- (instancetype)initWithDanceStyle:(NSString *)danceStyle
{
if (!(self = [super init]))
return nil;
_danceStyleText = [[ASTextNode alloc]init];
_danceStyleText.attributedString = [[NSAttributedString alloc]initWithString:[[danceStyle stringByReplacingOccurrencesOfString:@":" withString:@":\n"] uppercaseString] attributes:[self textStyleForDanceStyleBadge]];
[self addSubnode:_danceStyleText];
return self;
}
- (NSDictionary *)textStyleForDanceStyleBadge
{
UIFont *font = [UIFont fontWithName:@"AvenirNext-Medium" size:12.0f];
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.paragraphSpacing = 3.0f;
style.lineSpacing = 0.0f;
style.hyphenationFactor = 1.0;
style.alignment = NSTextAlignmentCenter;
UIColor *textColor = [UIColor colorWithRed:155/255.0f green:0.0f blue:26/255.0f alpha:1.0f];
return @{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: style,
NSForegroundColorAttributeName: textColor,
};
}
- (CGSize)calculateSizeThatFits:(CGSize)constrainedSize
{
CGSize handleSize = [_danceStyleText measure:CGSizeMake(constrainedSize.width,
constrainedSize.height)];
return CGSizeMake(handleSize.width+10.0f, handleSize.height+14.0f);
}
// do as little work as possible in main-thread layout
- (void)layout
{
CGSize handleSize = _danceStyleText.calculatedSize;
_danceStyleText.frame = CGRectMake(0.0f, 5.0f, handleSize.width, handleSize.height);
}
//
+ (void)drawRect:(CGRect)bounds withParameters:(id<NSObject>)parameters isCancelled:(asdisplaynode_iscancelled_block_t)isCancelledBlock isRasterizing:(BOOL)isRasterizing
{
if (!isRasterizing) {
[[UIColor whiteColor] set];
UIRectFill(bounds);
}
//// Color Declarations
UIColor* color2 = [UIColor colorWithRed: 0.608 green: 0 blue: 0.102 alpha: 1];
//// Rectangle Drawing
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(1, 1, bounds.size.width-2.0f, bounds.size.height-2.0f) cornerRadius: 4];
[color2 setStroke];
rectanglePath.lineWidth = 2;
[rectanglePath stroke];
}
Hmm, from the code my guess is that the text node is centering the glyphs within the drawable region of your original constraint, instead of its bounds. We have an optimization in text node where we don't recompute the layout when you re-set the bounds to be equal to a returned size from the TextKit backend. For the time being as a workaround you can probably set the width to be the size of the constraining size. I'll see if I can figure out how to fix or remove the optimization without destroying perf....
Great thanks, i'll do that for the time being.
+1 this is a problem for us.
In addition: When the text is only 1 line, it's not shown at all.
Code to reproduce:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{
NSForegroundColorAttributeName: [UIColor whiteColor],
NSFontAttributeName: [UIFont systemFontOfSize:17],
NSParagraphStyleAttributeName: paragraphStyle,
};
NSAttributedString *testString = [[NSAttributedString alloc] initWithString:@"This is a test." attributes:attributes];
text.attributedString = testString;
[text measure:CGSizeMake(self.view.frame.size.width, 21)];
text.frame = CGRectMake(200, 300, text.calculatedSize.width, text.calculatedSize.height);
[self.view addSubview:text.view];
OK, yep, definitely a bug, just repro'd locally and have a fix I'll put up in a minute. However, we should note that this kills one of our optimizations, but in the name of correctness I'm happy we found it! Thanks for reporting.
Fixed in #329.
@ocrickard, @secretiverhyme I faced the alignment issue after the fix was introduced in #329.
Here's my setup
- (instancetype) initWithUser: (SMUser*) user
{
if (self = [super init])
{
self.displaysAsynchronously = NO;
self.backgroundColor = [UIColor whiteColor];
self.nameTextNode = (
{
NSAttributedString* text = nil;
if ([user.fullName length])
text = [[NSAttributedString alloc] initWithString: user.fullName
attributes: [SMDirSpecialistCellNode _nameTextAttributes]];
ASTextNode* node = [ASTextNode new];
node.layerBacked = YES;
node.attributedString = text;
node.backgroundColor = [UIColor greenColor];
[self addSubnode: node];
node;
});
// and two other labels with same setup
}
return self;
}
#pragma mark -
#pragma mark Layout
- (CGSize) calculateSizeThatFits: (CGSize) constrainedSize
{
CGFloat width = constrainedSize.width - 40.0f;
CGFloat topOffsetY = 20.0f; //130.0f;
CGFloat height = topOffsetY;
if ([_nameTextNode.attributedString length])
{
[_nameTextNode measure: CGSizeMake(width, CGFLOAT_MAX)];
CGSize size = [_nameTextNode frameForTextRange: NSMakeRange(0, _nameTextNode.attributedString.length)].size;
height += ceilfCGSize(size).height;
}
if ([_positionTextNode.attributedString length])
{
[_positionTextNode measure: CGSizeMake(width, CGFLOAT_MAX)];
CGSize size = [_positionTextNode frameForTextRange: NSMakeRange(0, _positionTextNode.attributedString.length)].size;
height += ceilfCGSize(size).height;
}
if ([_bioTextNode.attributedString length])
{
[_bioTextNode measure: CGSizeMake(width, CGFLOAT_MAX)];
CGSize size = [_bioTextNode frameForTextRange: NSMakeRange(0, _bioTextNode.attributedString.length)].size;
height += ceilfCGSize(size).height;
}
height += 20.0f; //115.0f;
return CGSizeMake(constrainedSize.width, height);
}
- (void) layout
{
CGFloat width = self.calculatedSize.width;
CGFloat offsetY = 20.0f; //130.0f;
_nameTextNode.frame = (CGRect){CGPointMake((width - _nameTextNode.calculatedSize.width) / 2.0f, offsetY),
_nameTextNode.calculatedSize};
_positionTextNode.frame = (CGRect){CGPointMake((width - _positionTextNode.calculatedSize.width) / 2.0f,
CGRectGetMaxY(_nameTextNode.frame)), _positionTextNode.calculatedSize};
_bioTextNode.frame = (CGRect){CGPointMake((width - _bioTextNode.calculatedSize.width) / 2.0f,
CGRectGetMaxY(_positionTextNode.frame)), _bioTextNode.calculatedSize};
}
#pragma mark -
#pragma mark Text attributes
+ (NSDictionary*) _nameTextAttributes
{
NSMutableParagraphStyle* style = [NSMutableParagraphStyle new];
style.alignment = NSTextAlignmentCenter;
return @{NSForegroundColorAttributeName : [UIColor colorFromHex: 0x222222 alpha: 1.0f],
NSFontAttributeName : [UIFont helveticaNeueWithWeight: FontWeightMedium height: 26.0f],
NSParagraphStyleAttributeName : style};
}
What I've noticed is that - (void)setBounds:(CGRect)bounds is not called on ASTextNode, so the fix does not apply. I assume it happens because the node has a layer, here's an excerpt from - (void)setFrame:(CGRect)rect for ASDisplayNode:
- (void)setFrame:(CGRect)rect
{
_bridge_prologue;
// Frame is only defined when transform is identity because we explicitly diverge from CALayer behavior and define frame without transform
#if DEBUG
// Checking if the transform is identity is expensive, so disable when unnecessary. We have assertions on in Release, so DEBUG is the only way I know of.
ASDisplayNodeAssert(CATransform3DIsIdentity(self.transform), @"Must be an identity transform");
#endif
if (_layer && ASDisplayNodeThreadIsMain()) {
// THIS BRANCH GETS CALLED ON SETTING A FRAME ON ASTEXTNODE
CGPoint anchorPoint = _layer.anchorPoint;
_layer.bounds = CGRectMake(0, 0, rect.size.width, rect.size.height);
_layer.position = CGPointMake(rect.origin.x + rect.size.width * anchorPoint.x,
rect.origin.y + rect.size.height * anchorPoint.y);
} else {
CGPoint anchorPoint = self.anchorPoint;
self.bounds = CGRectMake(0, 0, rect.size.width, rect.size.height);
self.position = CGPointMake(rect.origin.x + rect.size.width * anchorPoint.x,
rect.origin.y + rect.size.height * anchorPoint.y);
}
}
So I tried to override - (void)setFrame:(CGRect)rect on ASTextNode instead of - (void)setBounds:(CGRect)bounds and it gave the result I was looking for (with same code as @ocrickard suggested):
- (void) setFrame: (CGRect) frame
{
[super setFrame: frame];
if (!CGSizeEqualToSize(frame.size, _constrainedSize)) {
// Our bounds have changed to a size that is not identical to our constraining size,
// so our previous layout information is invalid, and TextKit may draw at the
// incorrect origin.
_constrainedSize = CGSizeMake(-INFINITY, -INFINITY);
[self _invalidateRenderer];
}
}
Result:
So I wanted to ask whether that is a vital solution or not? Am I also right that my solution applies only if the node is built on main thread? (as for the moment I perform the reloads of my collectionView on main thread)
Also still seeing this after the fix was applied.
@nivanchikov good point on setFrame. We should also probably implement setFrame in addition to setBounds. Pull request would be awesome!
Re the bridge being the fault: yes, I believe you're probably right. If we implement both it should allow us to circumvent that issue though.
hey everyone, this is still an issue for me. Specifically, I'm on the 1.9.4 release and this is specific to ASTextNodes added to ASCellNodes. Anyone else seeing this again?
I'm also seeing this issue while rendering text node in cell nodes. Any solution will be highly appreciated. Thanks.
@gauravmnit07 try downgrading to 1.9.3. This problem also appeared to me when I to 1.9.5.
@EviluS @gauravmnit07 1.9.6 should actually have fixed these issues, so it's best to upgrade to that version.
@aaronschubert0 Yes it's working fine after updating to 1.9.6. Thanks for the update.