用Xcode以前本身自帶的coreText,coreImage,實現圖文混排,代碼量非常大,不容易理解,
而Textkit是iOS7新推出的類庫,其實是在之前推出的CoreText上的封裝, TextKit并沒有新增的類,他是在原有的文本顯示控件上的封裝,可以使用平時我們最喜歡使用的 UILabel,UITextField,UITextView里面就可以使用了。
//傳你需要處理的文本內容
NSString * str = @"nni-hao-textkit";
//創建NSMutableAttributedString
// 這是所有TextKit的載體,所有的信息都會輸入到NSAttributedString里面,然后將這個String輸入到Text控件里面就可以顯示了。
NSMutableAttributedString * attributed=[[NSMutableAttributedString alloc] initWithString:str];
//給所有字符設置字體為
//給所有字符設置字體為Zapfino,字體為30
[attributed addAttribute: NSFontAttributeName value: [UIFont fontWithName: @"Zapfino" size: 30]
range: NSMakeRange(0, str.length)];
//分段控制,最開始4個字符顏色設置成黃色
[attributed addAttribute: NSForegroundColorAttributeName value: [UIColor yellowColor] range: NSMakeRange(0, 4)];
//分段控制,第5個字符開始的3個字符,即第5、6、7字符設置為紅色
[attributed addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range: NSMakeRange(4, 3)];
//創建UITextView來顯示
UITextView * lable = [[UITextView alloc] initWithFrame:self.view.bounds];
lable.textAlignment = UITextAlignmentCenter;
lable.attributedText = attributed;
[self.view addSubview:lable];
//控制臺顯示

//*********************************************************************************
//創建圖片附件
NSTextAttachment *attach = [[NSTextAttachment alloc] init];
attach.image = [UIImage imageNamed:@"3.jpg"];
attach.bounds = CGRectMake(0, 70, 50, 50);
NSAttributedString * attachstring = [NSAttributedString attributedStringWithAttachment:attach];
[attributed appendAttributedString:attachstring];
//控制臺顯示:

新聞熱點
疑難解答