關(guān)于iOS文本展開(kāi)與收起,使用TextView 的簡(jiǎn)單實(shí)現(xiàn)方法

  • 1、如下示例,設(shè)置行距為5的利用富文本使用UITextView進(jìn)行操作
    這里沒(méi)有優(yōu)化,需要優(yōu)化的自行處理
/// 默認(rèn)收起的配置
- (void)configDidDownClose{
    NSString * contentsub = @"比特幣(Bitcoin)的概念最初由中本聰在2008年11月1日提出, [50]并于2009年1月3日正式誕生 [1]  。根據(jù)中本聰?shù)乃悸吩O(shè)計(jì)發(fā)布的開(kāi)源軟件以及建構(gòu)其上的P2P網(wǎng)絡(luò)。比特幣是一種P2P形式的數(shù)字貨幣 [52]  。比特幣的交易記錄公開(kāi)透明 [50]  。點(diǎn)對(duì)點(diǎn)的傳輸意味著一個(gè)去中心化的支付系統(tǒng)點(diǎn)對(duì)點(diǎn)的傳輸意味";
    self.noteTV.text = [NSString stringWithFormat:@"%@%@",contentsub,@"收起".ntes_localized] ;
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode =  NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = 5;
    paraStyle.hyphenationFactor = 0.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *attributes = @{NSFontAttributeName:FONT(14), NSParagraphStyleAttributeName:paraStyle
    };
    NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]init];
    
    NSDictionary *attDict1 = @{NSForegroundColorAttributeName:kColor_ox(0x333333)};
    
    NSAttributedString *attStr1 = [[NSAttributedString alloc] initWithString:[self.noteTV.text substringWithRange:NSMakeRange(0,self.noteTV.text.length - @"收起".ntes_localized.length )] attributes:attDict1];
    
    NSDictionary *attDict2 = @{NSForegroundColorAttributeName:kZhuTiColor};
    NSAttributedString *attStr2 = [[NSAttributedString alloc] initWithString:[self.noteTV.text substringWithRange:NSMakeRange(self.noteTV.text.length - @"收起".ntes_localized.length , @"收起".ntes_localized.length)] attributes:attDict2];
    
    
    [attributedText appendAttributedString:attStr1];
    [attributedText appendAttributedString:attStr2];
    [attributedText addAttributes:attributes range:NSMakeRange(0, self.noteTV.text.length)];
    /// 給富文本后面增加可操作的點(diǎn)擊鏈接通過(guò)代理來(lái)實(shí)現(xiàn)
    NSString *valueString = [[NSString stringWithFormat:@"didDownClose://%@", @"收起".ntes_localized] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [attributedText addAttribute:NSLinkAttributeName value:valueString range:NSMakeRange(self.noteTV.text.length - @"收起".ntes_localized.length , @"收起".ntes_localized.length)];
    
    _noteTV.attributedText = attributedText;
    
    CGFloat height = [self.noteTV.text getSpaceLabelWithFont:FONT(14) withWidth:SCREEN_WIDTH - 30];
    self.titleContentView = UIView.new;
    [self.titleContentView addSubview:self.noteTV];
    self.titleContentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, height + 15);
    self.noteTV.frame = CGRectMake(15, 15, SCREEN_WIDTH - 30, height);
    [self.tableView setTableHeaderView:self.titleContentView];
}
/// 默認(rèn)打開(kāi)的配置
- (void)configDidOpenClose{
    NSString * contentsub = @"比特幣(Bitcoin)的概念最初由中本聰在2008年11月1日提出, [50]并于2009年1月3日正式誕生 [1]  。根據(jù)中本聰?shù)乃悸吩O(shè)計(jì)發(fā)布的開(kāi)源軟件以及建構(gòu)其上的P2P網(wǎng)絡(luò)。比特幣是一種P2P形式的數(shù)字貨幣 [52]  。比特幣的交易記錄公開(kāi)透明 [50]  。點(diǎn)對(duì)點(diǎn)的傳輸意味著一個(gè)去中心化的支付系統(tǒng)點(diǎn)對(duì)點(diǎn)的傳輸意味";
    
    
    NSString *tempStr = [self stringByTruncatingString:contentsub suffixStr:@"...全部展開(kāi)" font:FONT(14) width:SCREEN_WIDTH - 30 num:3];
    self.noteTV.text = tempStr;
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode =  NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = 5;
    paraStyle.hyphenationFactor = 0.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *attributes = @{NSFontAttributeName:FONT(14), NSParagraphStyleAttributeName:paraStyle
    };
    NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]init];
    
    NSDictionary *attDict1 = @{NSForegroundColorAttributeName:kColor_ox(0x333333)};
    
    NSAttributedString *attStr1 = [[NSAttributedString alloc] initWithString:[tempStr substringWithRange:NSMakeRange(0,tempStr.length - @"全部展開(kāi)".ntes_localized.length )] attributes:attDict1];
    
    NSDictionary *attDict2 = @{NSForegroundColorAttributeName:kZhuTiColor};
    NSAttributedString *attStr2 = [[NSAttributedString alloc] initWithString:[tempStr substringWithRange:NSMakeRange(tempStr.length - @"全部展開(kāi)".ntes_localized.length , @"全部展開(kāi)".ntes_localized.length)] attributes:attDict2];
    
    
    [attributedText appendAttributedString:attStr1];
    [attributedText appendAttributedString:attStr2];
    [attributedText addAttributes:attributes range:NSMakeRange(0, tempStr.length)];
    /// 給富文本后面增加可操作的點(diǎn)擊鏈接通過(guò)代理來(lái)實(shí)現(xiàn)
    NSString *valueString = [[NSString stringWithFormat:@"didOpenClose://%@", @"全部展開(kāi)".ntes_localized] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [attributedText addAttribute:NSLinkAttributeName value:valueString range:NSMakeRange(tempStr.length - @"全部展開(kāi)".ntes_localized.length , @"全部展開(kāi)".ntes_localized.length)];
    
    _noteTV.attributedText = attributedText;
    
    CGFloat height = [tempStr getSpaceLabelWithFont:FONT(14) withWidth:SCREEN_WIDTH - 30];
    self.titleContentView = UIView.new;
    [self.titleContentView addSubview:self.noteTV];
    self.titleContentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, height + 15);
    self.noteTV.frame = CGRectMake(15, 15, SCREEN_WIDTH - 30, height);
    [self.tableView setTableHeaderView:self.titleContentView];
    
}
  • 2、核心代碼
/// 將文本按長(zhǎng)度度截取并加上指定后綴
/// @param str 文本
/// @param suffixStr 指定后綴
/// @param font 文本字體
/// @param textWidth 文本長(zhǎng)度
/// @param num 多少行
- (NSString*)stringByTruncatingString:(NSString *)str suffixStr:(NSString *)suffixStr font:(UIFont *)font width:(CGFloat)textWidth num:(NSInteger)num {
    if (!str) return nil;
    CGFloat width = 0;
    int k = 0;
    CGFloat suffixWidth = [suffixStr sizeWithAttributes:@{NSFontAttributeName:font}].width;
    if (str  && [str isKindOfClass:[NSString class]]) {
        for (int i=0; i< [str length];i++){

            NSString *tempStr = [str substringToIndex:i + 1];
           
            CGSize size = [tempStr sizeWithAttributes:@{NSFontAttributeName:font}];
            if ((size.width - width) > textWidth) {
                tempStr = [str substringToIndex:i];
                if (k == num - 1) {
                    str = tempStr;
                     for (int i=(int)[str length] - (int)[suffixStr length]; i< [str length];i = i - (int)[suffixStr length]){
                         tempStr = [str substringToIndex:i];
                         CGSize size = [tempStr sizeWithAttributes:@{NSFontAttributeName:font}];
                         if(size.width - width + suffixWidth  < textWidth){
                             tempStr = [NSString stringWithFormat:@"%@%@", tempStr,suffixStr];
                             str = tempStr;
                             break;
                         }
                     }

                    break;
                }
                width = size.width ;

                k ++;
            }
        }
    }
    return str;
}
  • 3、通過(guò)UITextView的代理方法來(lái)實(shí)現(xiàn)
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"didOpenClose"]) {
        [self configDidOpenClose];
        return NO;
    }
    if ([[URL scheme] isEqualToString:@"didDownClose"]) {
        [self configDidDownClose];
        return NO;
    }
    return YES;
}
  • 4、附上計(jì)算文本高度
- (CGFloat)getSpaceLabelWithFont:(UIFont*)font withWidth:(CGFloat)width {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = 5;
    paraStyle.hyphenationFactor = 0.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                          };
    
    CGSize size = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    
    return size.height;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容