web-dev-qa-db-fra.com

Comment puis-je définir la couleur et l'alignement du texte attribué dans un UITextView dans iOS 7?

Le formatage de mes textViews a bien fonctionné dans iOS 6, mais plus dans iOS 7. Je comprends qu'avec Text Kit, une grande partie des éléments sous le capot a changé. C'est devenu vraiment assez déroutant, et j'espère que quelqu'un pourra aider à le redresser un peu en m'aidant avec quelque chose d'aussi simple que cela.

Mon UITextView statique a reçu à l'origine une valeur pour ses propriétés textColor et textAlignment. Ensuite, j'ai créé un NSMutableAttributedString, je lui ai attribué des attributs, puis je l'ai affecté à la propriété attributedText de textView. L'alignement et la couleur ne prennent plus effet dans iOS 7.

Comment puis-je réparer cela? Si ces propriétés n'ont aucun effet, alors pourquoi existent-elles encore? Voici la création de textView:

UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];

NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSParagraphStyleAttributeName value:font range:NSMakeRange(0, title.length)];
titleView.attributedText = title;

[self.view addSubview:titleView];
33
Joe

Curieux, les propriétés sont prises en compte pour UILabel mais pas pour UITextView

Pourquoi n'ajoutez-vous pas simplement des attributs de couleur et d'alignement à la chaîne attribuée, comme vous le faites avec la police?

Quelque chose comme:

NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];

//add color
[title addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, title.length)];

//add alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[title addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, title.length)];

titleView.attributedText = title;

Edit: Attribuez d'abord le texte, puis changez les propriétés et ainsi cela fonctionne.

UITextView *titleView = [[UITextView alloc]initWithFrame:CGRectMake(0, 90, 1024, 150)];

//create attributed string and change font
NSMutableAttributedString *title = [[NSMutableAttributedString alloc]initWithString:@"Welcome"];
UIFont *font = [UIFont fontWithName:@"Avenir-Light" size:60];
[title addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];

//assign text first, then customize properties
titleView.attributedText = title;
titleView.textAlignment = NSTextAlignmentCenter;
titleView.textColor = [UIColor whiteColor];
66
jlhuertas