iOS - проблема с добавлением моего фрейма CATextLayer в UIScrollView

Я пытаюсь добавить свой кадр CATextLayer в UIScrollView, чтобы получить некоторую прокрутку. Я пытался использовать технику, упомянутую здесь ( как я могу сделать мой объект CATextLayer Scrollable как UITextView?) Безуспешно.

На самом деле из-за (предложенных) трех строк, которые я добавил в свой код, мой CATextLayer больше не отображается.

Я приложил свой код ниже и отметил эти 3 строки. Возможно, кто-то может помочь мне разобраться с этим или даже предложить лучший способ подойти к этому:-)

// Create the scrool view (FIRST LINE ADDED)
UIScrollView* scrollLayer = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, 500.0, 500.0)];

// Create the new layer object
boxLayer = [[CATextLayer alloc] init];

// Give it a size
[boxLayer setBounds:CGRectMake(0.0, 0.0, 500.0, 500.0)];

// Give it a location
[boxLayer setPosition:CGPointMake(300.0, 350.0)];

// Make half-transparent red the background color for the layer
UIColor *reddish = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.1];

// Get CGColor object with the same color values
CGColorRef cgReddish = [reddish CGColor];
[boxLayer setBackgroundColor:cgReddish];

// Make it a sublayer on the view's layer
[self.view.layer addSublayer:boxLayer];

// Create string
NSString *text2 = @"The article was about employment.\nHe leafed through it in an instant.\nHis feeling of anxiety resurfaced and he closed the magazine.\n\n-Hm…, he breathed.\n\n-Have you been looking for work long?, asked the stranger at his side.\nThe article was about employment.\nHe leafed through it in an instant.\nHis feeling of anxiety resurfaced and he closed the magazine.\n\n-Hm…, he breathed.\n\n-Have you been looking for work long?, asked the stranger at his side.\nThe article was about employment.\nHe leafed through it in an instant.\nHis feeling of anxiety resurfaced and he closed the magazine.\n\n-Hm…, he breathed.\n\n-Have you been looking for work long?, asked the stranger at his side.";


// Set font type
[boxLayer setFont:@"MarkerFelt-Thin"];

// Set font size
[boxLayer setFontSize:20.0];

// Text is left justified
[boxLayer setAlignmentMode:kCAAlignmentLeft];

// Text is wrapped
boxLayer.wrapped = YES;

// Assign string to layer
[boxLayer setString:text2];

// Define the text size (SECOND LINE ADDED)
scrollLayer.contentSize = CGSizeMake(500, 1000);

// Set the text layer as a sub layer of the scroll view (THIRD LINE ADDED)
[scrollLayer.layer addSublayer:boxLayer];

1 ответ

Решение

В соответствии с нашей дискуссией о другой дискуссии, мне интересно, стоит ли вам добавлять CATextLayer объекты на всех. Можете добавить UILabel объекты, например. Например, давайте добавим серию UILabel объекты для нашего вида прокрутки:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if (!self.addedLabels)
    {
        [self addLabelsToScrollView:self.scrollView];
        self.addedLabels = YES;
    }
}

- (void)addLabelsToScrollView:(UIScrollView *)scrollView
{
    NSArray *gettysburgAddress = @[
                                   @"Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.",
                                   @"Now we are engaged in a great civil war, testing whether that nation, or any nation, so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.",
                                   @"But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth."
                                  ];

    CGFloat y = 0.0;
    UIFont *font = [UIFont fontWithName:@"MarkerFelt-Thin" size:20.0];
    CGSize maxSize = CGSizeMake(scrollView.frame.size.width, 10000.0);

    for (NSString *line in gettysburgAddress)
    {
        CGSize labelSize = [line sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
        CGRect labelFrame = CGRectMake(0.0, y, labelSize.width, labelSize.height);
        UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
        label.font = font;
        label.text = line;
        label.numberOfLines = 0;
        [scrollView addSubview:label];

        y += labelSize.height + 16.0;
    }

    scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, y);
}

Или даже проще, чем добавление UILabel возражает против UIScrollViewВы могли бы просто использовать UITextView:

- (void)updateTextView
{
    NSArray *gettysburgAddress = @[
                                   @"Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.",
                                   @"Now we are engaged in a great civil war, testing whether that nation, or any nation, so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.",
                                   @"But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth."
                                  ];

    NSString *text = [gettysburgAddress componentsJoinedByString:@"\n\n"];

    self.textView.text = text;
    self.textView.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:20.0];
    self.textView.editable = NO;
}

Все сводится к тому, действительно ли вам нужно использовать CATextLayer,

Другие вопросы по тегам