AsyncDisplayKit icon indicating copy to clipboard operation
AsyncDisplayKit copied to clipboard

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

Open aaronschubert0 opened this issue 12 years ago • 16 comments

See: screen shot 2014-11-05 at 14 18 53

aaronschubert0 avatar Nov 05 '14 14:11 aaronschubert0

The red is the background color of the ASTextNode

aaronschubert0 avatar Nov 05 '14 14:11 aaronschubert0

Can you please provide the sample code you used to produce this?

ocrickard avatar Nov 05 '14 19:11 ocrickard

.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];
}

aaronschubert0 avatar Nov 05 '14 22:11 aaronschubert0

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....

ocrickard avatar Nov 06 '14 15:11 ocrickard

Great thanks, i'll do that for the time being.

aaronschubert0 avatar Nov 06 '14 16:11 aaronschubert0

+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];

mtitolo avatar Feb 23 '15 20:02 mtitolo

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.

ocrickard avatar Feb 24 '15 18:02 ocrickard

Fixed in #329.

secretiverhyme avatar Feb 24 '15 20:02 secretiverhyme

@ocrickard, @secretiverhyme I faced the alignment issue after the fix was introduced in #329.

img_0324

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: img_0325

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)

nivanchikov avatar Mar 04 '15 21:03 nivanchikov

Also still seeing this after the fix was applied.

mtitolo avatar Mar 12 '15 23:03 mtitolo

@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.

ocrickard avatar Mar 20 '15 03:03 ocrickard

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?

adcooley avatar Jan 12 '16 19:01 adcooley

I'm also seeing this issue while rendering text node in cell nodes. Any solution will be highly appreciated. Thanks.

gauravmnit07 avatar Jan 23 '16 14:01 gauravmnit07

@gauravmnit07 try downgrading to 1.9.3. This problem also appeared to me when I to 1.9.5.

gkpetrov89 avatar Jan 26 '16 10:01 gkpetrov89

@EviluS @gauravmnit07 1.9.6 should actually have fixed these issues, so it's best to upgrade to that version.

aaronschubert0 avatar Jan 26 '16 11:01 aaronschubert0

@aaronschubert0 Yes it's working fine after updating to 1.9.6. Thanks for the update.

gauravmnit07 avatar Jan 27 '16 11:01 gauravmnit07