Question

I have used CATextLayer for Displaying bold and Normal text together.Now some time i am getting long text from the Web Service response so i am not able to display complete text.Can any one please help me what should be the way to make CATextLayer object Scrollable like textview.Please suggest me any solution regarding this.I have also take reference from Here but it's not working for me. I am using this code:

/* Create the text layer on demand */

if (!_textLayer) {
    _textLayer = [[CATextLayer alloc] init];
    //_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString
    _textLayer.backgroundColor = [UIColor clearColor].CGColor;
    _textLayer.wrapped = YES;
    //CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller
    _textLayer.frame = CGRectMake(5,325, 310, 90);
    _textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :)
    _textLayer.alignmentMode = kCAAlignmentJustified;
    _textLayer.masksToBounds = YES;
    [self.view.layer addSublayer:_textLayer];
}

At bottom I have also tried to add my _textLayer to UITextView's layer as well instead of self.view.layer.

Please suggest How could i achieve this feature?

Was it helpful?

Solution

You can just add your CATextLayer to UIScrollView and get scrolling for free. Set scrollview's frame as needed and contentSize as your CATextLayer frame and add it to scroll's layer, something like this (not actually working code):

UIScrollView* scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,100,100)];
CATextLayer* layer = [CATextLayer layer];
//layer init code goes here
scroll.contentSize = CGSizeMake(1000,1000);//or your actual text layer size
[scroll.layer addSublayer:layer];

and you are done! Don't forget to add scroll as your view subview.

OTHER TIPS

Use NSString's method sizeWithFont:constrainedToSize: to obtain bounding rect for your text with given font, then set layer's frame using this size:

NSString* myString = ....;
CGSize size =     [myString sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(100, 100)];
_textlayer.frame = CGRectMake(0,0,size.width,size.height);

Just do not forget to use the appropriate font / constraint size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top