IPhone CATextLayer не отображает текст
Я просто пытался добавить 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;
}
Ответы
Ответ 1
Для 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 будет отображаться как черный, независимо от того, какой текст вы установили.
Ответ 2
Измените код следующим образом:
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. Таким образом, вы знаете, что ваш взгляд загружен и действителен и теперь может добавлять к нему слои.
Ответ 3
Вы можете настроить 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 в ваш класс вида. Спасибо...
Ответ 4
В соответствии с документами цвет текста по умолчанию CATextLayer
по умолчанию является белым. Белый на белом фоне трудно увидеть.
Ответ 5
попробуйте следующее:
self.view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[self.view setWantsLayer:YES];
self.view.backgroundColor = [UIColor blueColor];
Ответ 6
Swift
Вот пример, показывающий представление с CATextLayer с использованием специального шрифта с цветным текстом.
![введите описание изображения здесь]()
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)
}
}
Мой более полный ответ здесь.
Ответ 7
Вы должны (встречно-интуитивно) вызывать textLayer.display()
или textLayer.displayIfNeeded()
после завершения инициализации или всякий раз, когда вы хотите, чтобы текст был нарисован.