那些 iOS 7 中容易被忽视的新特性总结

本文介绍如何在iOS应用中利用NSAttributedString轻松解析和显示HTML内容,替代使用Webview的方法,并提供示例代码说明如何实现。
转载自:  http://mobile.51cto.com/hot-435208.htm


 14.使用NSAttributedString显示HTML


在app中使用Webviews有时会让人非常沮丧,即使只是显示少量的HTMLneirong ,Webviews也会消耗大量的内容。现在iOS7让这些变得简单了,你可以从用少量代码在HTML文件中创建一个NSAttributedString,比如:


    NSString *html = @”<bold>Wow!</bold> Now <em>iOS</em> can create <h3>NSAttributedString</h3> from HTMLs!”; 
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}; 
      
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] 
    options:options documentAttributes:nil error:nil]; 
      
 
现在你可以在任意的UIKit对象上使用NSAttributedString 了,比如说是一个UILabel或是一个UITextField,见以下代码: 
 
    #import <SSKeychain.h> 
      
    - (BOOL)saveCredentials:(NSError **)error { 
        SSKeychainQuery *query = [[SSKeychainQuery alloc] init]; 
        query.password = @”MySecretPassword”; 
        query.service = @”MyAwesomeService”; 
        query.account = @”John Doe”; 
        query.synchronizable = YES; 
        return [query save:&error]; 
    } 
      
    - (NSString *)savedPassword:(NSError **)error { 
        SSKeychainQuery *query = [[SSKeychainQuery alloc] init]; 
        query.service = @”MyAwesomeService”; 
        query.account = @”John Doe”; 
        query.synchronizable = YES; 
        query.password = nil; 
        if ([query fetch:&error]) { 
            return query.password; 
        } 
        return nil; 
注意:NSHTMLTextDocumentType 只是NSDocumentTypeDocumentAttribute key一种可能的值。你还可以使用NSPlainTextDocumentType,NSRTFTextDocumentType或是 NSRTFDTextDocumentType。


你还可以从NSAttributedString中创建一个HTML字符串,如下:


NSAttributedString *attrString; // from previous code 
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}; 
  
NSData *htmlData = [attrString dataFromRange:NSMakeRange(0, [attrString length]) documentAttributes:options error:nil]; 
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding]; 
现在你估计在app中会更多的使用HTML了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值