iPhone CATextLayer не показывает свой текст - PullRequest
12 голосов
/ 18 июня 2010

Я просто пытался добавить CATextlayer в слой UIView.Однако, согласно следующему коду, я получаю только цвет фона CATextlayer для отображения в UIView без какого-либо текста.Просто интересно, что я пропустил, чтобы отобразить текст.

Может кто-нибудь предложить подсказку / образец, как использовать CATextlayer?

  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
        if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
            // Custom initialization

            CATextLayer *TextLayer = [CATextLayer layer];
            TextLayer.bounds = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
            TextLayer.string = @"Test";
            TextLayer.font = [UIFont boldSystemFontOfSize:18].fontName;
            TextLayer.backgroundColor = [UIColor blackColor].CGColor;
            TextLayer.wrapped = NO;

            //TextLayer.backgroundColor = [UIColor blueColor];
            self.view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
            self.view.backgroundColor = [UIColor blueColor];
            [self.view.layer addSublayer:TextLayer];
            [self.view.layer layoutSublayers];

        }
        return self;
    }

Ответы [ 7 ]

7 голосов
/ 03 мая 2013

Для iOS 5 и выше можно использовать CATextLayer следующим образом:

CATextLayer *textLayer = [CATextLayer layer];
textLayer.frame = CGRectMake(144, 42, 76, 21);
textLayer.font = CFBridgingRetain([UIFont boldSystemFontOfSize:18].fontName);
textLayer.fontSize = 18;
textLayer.foregroundColor = [UIColor redColor].CGColor;
textLayer.backgroundColor = [UIColor yellowColor].CGColor;
textLayer.alignmentMode = kCAAlignmentCenter;
textLayer.string = @"BAC";
[self.view.layer addSublayer:textLayer];

Вы можете добавить этот код в любую понравившуюся вам функцию. Специально здесь необходимо правильное назначение шрифта , иначе ваш CATextLayer будет отображаться как черный независимо от того, какой текстовый цвет вы установили.

5 голосов
/ 23 июля 2010

Измените свой код на это:

CATextLayer *TextLayer = [CATextLayer layer];
TextLayer.bounds = CGRectMake(0.0f, 0.0f, 100.0f, 100.0f);
TextLayer.string = @"Test";
TextLayer.font = [UIFont boldSystemFontOfSize:18].fontName;
TextLayer.backgroundColor = [UIColor blackColor].CGColor;
TextLayer.position = CGPointMake(80.0, 80.0f);
TextLayer.wrapped = NO;
[self.view.layer addSublayer:TextLayer];

Вы также должны делать это в -viewDidLoad контроллера представления. Таким образом, вы узнаете, что ваше представление загружено и допустимо, и теперь в него можно добавлять слои.

4 голосов
/ 08 августа 2016

Swift

Вот пример, который показывает представление с CATextLayer с использованием пользовательского шрифта с цветным текстом.

enter image description here

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Attributed string
        let myAttributes = [
            NSFontAttributeName: UIFont(name: "Chalkduster", size: 30.0)! , // font
            NSForegroundColorAttributeName: UIColor.cyanColor()             // text color
        ]
        let myAttributedString = NSAttributedString(string: "My text", attributes: myAttributes )

        // Text layer
        let myTextLayer = CATextLayer()
        myTextLayer.string = myAttributedString
        myTextLayer.backgroundColor = UIColor.blueColor().CGColor
        myTextLayer.frame = myView.bounds
        myView.layer.addSublayer(myTextLayer)
    }
} 

Мой полный ответ здесь .

2 голосов
/ 15 февраля 2012

Вы можете настроить CLTextLayer. Вот так:

    CATextLayer *aTextLayer_= [[CATextLayer alloc] init];

aTextLayer_.frame =CGRectMake(23.0, 160.0, 243.0, 99.0);

aTextLayer_.font=CTFontCreateWithName( (CFStringRef)@"Courier", 0.0, NULL);

    aTextLayer_.string = @"You string put here";

aTextLayer_.wrapped = YES;

aTextLayer_.foregroundColor = [[UIColor greenColor] CGColor];

aTextLayer_.fontSize = 15.f;

   aTextLayer_.backgroundColor = [UIColor blackColor].CGColor;

aTextLayer_.alignmentMode = kCAAlignmentCenter;

[self.view.layer addSublayer:aTextLayer_];

Не забывайте импортировать CoreText / CoreText.h в свой класс представления.Спасибо ...

1 голос
/ 24 августа 2017

Вы должны (нелогично) вызвать textLayer.display() или textLayer.displayIfNeeded() после завершения инициализации или всякий раз, когда вы хотите, чтобы он нарисовал текст.

0 голосов
/ 19 июля 2010

попробуйте это:

self.view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[self.view setWantsLayer:YES];
self.view.backgroundColor = [UIColor blueColor];
0 голосов
/ 18 июня 2010

Согласно документам, цвет текста по умолчанию CATextLayer - белый.Белое на белом плохо видно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...