iOS與Html富文本(純文本)的那點(diǎn)事

直接將富文本轉(zhuǎn)成普通文本展示

//將Html字符串轉(zhuǎn)成OC的富文本對(duì)象
NSAttributedString *attStr = [[NSAttributedString alloc] initWithData:@"你想解析的html字符串" dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
//resultStr 就是我們要的普通字符串
NSString * resultStr=attStr.string;

通過(guò)原生控件的attributedText屬性展示

label.attributedText = attStr;
textField.attributedText=attStr;
textView.attributedText=attStr;

計(jì)算富文本的高度

+ (CGFloat)getStrHeightWithAttributeStr:(NSAttributedString *)string
                                    viewWidth:(CGFloat)viewWidth{
    if (string.length == 0) {
        return 0;
    }
     CGSize size  = [string boundingRectWithSize:CGSizeMake(viewWidth, MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  context:nil].size;
    return ceil(size.height);
}

計(jì)算富文本的長(zhǎng)度

+ (CGFloat)getStrWidthWithAttributeStr:(NSAttributedString *)string
                                  viewHeight:(CGFloat)viewHeight{
    if (string.length == 0) {
        return 0;
    }
    CGSize size  = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, viewHeight) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return ceil(size.width);
}

UILabel實(shí)現(xiàn)點(diǎn)擊文字跳鏈效果(有相關(guān)需求的可以參照一下,編程思路應(yīng)該是一致的)

1.獲取用戶點(diǎn)擊事件

我這里是子類(lèi)化一個(gè)label,在其初始化的方法里添加了一個(gè)單擊手勢(shì)

@interface LSHtmlLabel ()
@property (nonatomic,strong)NSTextStorage *textStorage;
@property (nonatomic,strong)NSLayoutManager *layoutManager;
@property (nonatomic,strong)NSTextContainer *textContainer;
@end 

@implementation LSHtmlLabel
-(instancetype)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self)
    {
        self.userInteractionEnabled=YES;
        self.numberOfLines=0;
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [self addGestureRecognizer:tap];
        self.textStorage = [NSTextStorage new];
        self.layoutManager = [NSLayoutManager new];
        self.textContainer = [NSTextContainer new];
        [self.textStorage addLayoutManager:self.layoutManager];
        [self.layoutManager addTextContainer:self.textContainer];
    }
    return self;
}

2.通過(guò)事件獲取用戶點(diǎn)擊的在UILabel上的位置,通過(guò)計(jì)算得出用戶點(diǎn)擊的文字及文字的下標(biāo)

-(void)tapClick:(UITapGestureRecognizer * )gesture
{
    CGPoint location=[gesture locationInView:self];
    self.textContainer.size = self.bounds.size;
    self.textContainer.lineFragmentPadding = 0;
    self.textContainer.maximumNumberOfLines = self.numberOfLines;
    self.textContainer.lineBreakMode = self.lineBreakMode;
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    NSRange textRange = NSMakeRange(0, attributedText.length);
    [attributedText addAttribute:NSFontAttributeName value:self.font range:textRange];
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.alignment = self.textAlignment;
    [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:textRange];
    [self.textStorage setAttributedString:attributedText];
       
        
    CGSize textSize = [self.layoutManager usedRectForTextContainer:self.textContainer].size;
        //    location.x -= (CGRectGetWidth(self.label.frame) - textSize.width) / 2;
        location.y -= (CGRectGetHeight(self.frame) - textSize.height) / 2;
        
    NSUInteger glyphIndex = [self.layoutManager glyphIndexForPoint:location inTextContainer:self.textContainer];
    CGFloat fontPointSize = self.font.pointSize;
    [self.layoutManager setAttachmentSize:CGSizeMake(fontPointSize, fontPointSize) forGlyphRange:NSMakeRange(self.text.length - 1, 1)];
    NSAttributedString *attributedSubstring = [self.attributedText attributedSubstringFromRange:NSMakeRange(glyphIndex, 1)];
    CGRect glyphRect = [self.layoutManager boundingRectForGlyphRange:NSMakeRange(glyphIndex, 1)
                                                                    inTextContainer:self.textContainer];
    if (!CGRectContainsPoint(glyphRect, location)) {
        if (CGRectContainsPoint(CGRectMake(0, 0, textSize.width, textSize.height), location)) {
        }
        NSLog(@"沒(méi)找到呢,該怎么辦才好呢");
        return;
    }    
    //此處我通過(guò)block塊返回的兩個(gè)值
    _clickLabelBlock(self,(unsigned long)glyphIndex,attributedSubstring);  
}

3.拿到用戶點(diǎn)擊的文字下標(biāo),富文本文字此時(shí)你就可以為所欲為啦

  LSHtmlLabel * label=[[LSHtmlLabel alloc]initWithFrame:_htmlLabel.frame];
    [label setClickLabelBlock:^(LSHtmlLabel * _Nonnull label, NSUInteger index, NSAttributedString * _Nonnull attributedSubstring) {
        NSLog(@"%@",attributedSubstring);
        //獲取文字屬性字典
        NSRange range = NSMakeRange(0, 1);
        NSDictionary*dic = [attributedSubstring attributesAtIndex:0 effectiveRange:&range];
        //判斷超鏈接是否存在 添加對(duì)應(yīng)的處理邏輯
        if (dic[@"NSLink"])
        {
            NSLog(@"%@",dic[@"NSLink"]);
        }        
    }];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市梯轻,隨后出現(xiàn)的幾起案子坠敷,更是在濱河造成了極大的恐慌,老刑警劉巖表谊,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件橘沥,死亡現(xiàn)場(chǎng)離奇詭異毅戈,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)检痰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門(mén)包归,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人铅歼,你說(shuō)我怎么就攤上這事公壤』豢桑” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵厦幅,是天一觀的道長(zhǎng)沾鳄。 經(jīng)常有香客問(wèn)我,道長(zhǎng)确憨,這世上最難降的妖魔是什么译荞? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮休弃,結(jié)果婚禮上吞歼,老公的妹妹穿的比我還像新娘。我一直安慰自己塔猾,他們只是感情好浆熔,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著桥帆,像睡著了一般。 火紅的嫁衣襯著肌膚如雪慎皱。 梳的紋絲不亂的頭發(fā)上老虫,一...
    開(kāi)封第一講書(shū)人閱讀 52,156評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音茫多,去河邊找鬼祈匙。 笑死,一個(gè)胖子當(dāng)著我的面吹牛天揖,可吹牛的內(nèi)容都是我干的夺欲。 我是一名探鬼主播,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼今膊,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼些阅!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起斑唬,我...
    開(kāi)封第一講書(shū)人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤市埋,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后恕刘,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體缤谎,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年褐着,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了坷澡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡含蓉,死狀恐怖频敛,靈堂內(nèi)的尸體忽然破棺而出项郊,到底是詐尸還是另有隱情,我是刑警寧澤姻政,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布呆抑,位于F島的核電站,受9級(jí)特大地震影響汁展,放射性物質(zhì)發(fā)生泄漏鹊碍。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一食绿、第九天 我趴在偏房一處隱蔽的房頂上張望侈咕。 院中可真熱鬧,春花似錦器紧、人聲如沸耀销。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)熊尉。三九已至,卻和暖如春掌腰,著一層夾襖步出監(jiān)牢的瞬間狰住,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工齿梁, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留催植,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓勺择,卻偏偏與公主長(zhǎng)得像创南,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子省核,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容