CATextLayer number of lines?

2k Views Asked by At

My CATextlayer support only 1 line otherwise the text is cut.

trying to set text content like UILabel Behaviour... is it possible?

  1. set "number of lines"

  2. adjust text size by static CATextLayer frame

enter image description here

CATextLayer *text_layer= [[CATextLayer alloc] init];
[text_layer setBackgroundColor:[UIColor clearColor].CGColor];
[text_layer setBackgroundColor:[UIColor blueColor].CGColor];
[text_layer setForegroundColor:layers.textColor.CGColor];
[text_layer setAlignmentMode:kCAAlignmentCenter];
[text_layer setBorderColor:layers.borderColor.CGColor];
[text_layer setFrame:CGRectMake(0,0,200,50)]; //note: frame must be static
[text_layer setString:@"thank you for your respond"];
 text_layer.wrapped = YES;
[text_layer setAlignmentMode:kCAAlignmentCenter];
1

There are 1 best solutions below

2
On

Your problem is this line right here, [text_layer setFrame:CGRectMake(0,0,200,50)];. I don't think a CATextLayer would lay itself out to accommodate multiple lines. It will only re-draw the text to wrap within the layer's bounds. Try adjusting your text layer's frame based on the text being set. You can create a UILabel instance, to calculate the frame for having multiline text with word wrapping and set it to your CATextLayer instance.

Here's a UILabel category to calculate text size for multiline text with word wrapping:

@interface UILabel (Height)

- (CGSize)sizeForWrappedText;

@end

@implementation UILabel (Height)

- (CGSize)sizeForWrappedText {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.bounds.size.width, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.font = self.font;
    label.text = self.text;
    [label sizeToFit];
    return label.frame.size;
}

@end

Create a UILabel instance, and use the sizeForWrappedText to get the size. Something like this:

// Make sure the someFrame here has the preferred width you want for your text_layer instance.
UILabel *label = [[UILabel alloc] initWithFrame:someFrame];
[label setText:@"My awesome text!"];

CGRect frame = text_layer.frame;
frame.size = [label sizeForWrappedText];
[text_layer setFrame:frame];