用TextKit實現表情,圖片,文字混排,textkit表情
用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];
//控制台顯示: