如何在其中创建带有粗体和普通文本的UILabel或UITextView?

6 iphone uitextview uilabel ios

我正在尝试在里面创建一个UILabelUITextView带有粗体和普通文本.

我已经浏览了attributesstring但是当我在自定义单元格的标签中设置它时,它不会显示任何文本.

我也使用过该UITextView setContentToHTMLString:方法,但它没有记录,app被拒绝了.

任何人都可以为此提供某种解决方案吗?

Mic*_*ann 5

直到iOS 6.0,您无法使用普通的UILabel或UITextView执行此操作,但您可以将NSAttributedString对象与一些可能的开源解决方案一起使用.

TTAttributedLabelOHAttributedLabel.

iOS SDK中内置了一个解决方案,您也可以使用CATextLayer,它具有可以设置为NSAttributedString的字符串属性.

而且,就像下面的评论者所说,是的,你可以用" attributedText"属性做到这一点.Horray!(对于Apple倾听开发人员经常重复的功能请求)


Bhu*_*dra 5

使用" NSAttributedString"在单个标签中设置多个字体文本并使用CATextLayer它来呈现它:

只是 #import "NSAttributedString+Attributes.h"

然后像这样实现它:

NSString *string1 = @"Hi";

NSString *string2 = @"How are you ?";

NSMutableAttributedString *attr1 = [NSMutableAttributedString attributedStringWithString:string1];

[attr1 setFont:[UIFont systemFontOfSize:20]];

NSMutableAttributedString *attr2 = [NSMutableAttributedString attributedStringWithString:string2]

[attr2 setFont:[UIFont boldSystemFontOfSize:20]];

[attr1 appendAttributedString:attr2]

CATextLayer *textLayer = [CATextLayer layer];

layer.string = attr1;

layer.contentsScale = [[UIScreen mainScreen] scale];

(Your_text_label).layer = textLayer;

OR (if you want to render on a view directly)

[(Your_View_Name).layer addSublayer:textLayer];
Run Code Online (Sandbox Code Playgroud)