ibireme / YYText

Powerful text framework for iOS to display and edit rich text.
MIT License
8.86k stars 1.7k forks source link

AttributeString不显示 #321

Closed terrispg closed 8 years ago

terrispg commented 8 years ago

snip20160516_1 文字莫名其妙的被添加的附件遮住了?

ibireme commented 8 years ago

贴一下相关使用代码看看(比如用的是 YYLabel 还是 YYTextView、字符串和附件怎么组装的)。

terrispg commented 8 years ago
GBAttributedLabel.h

#import <UIKit/UIKit.h>
#import <YYText.h>
typedef NS_ENUM(NSInteger,GBAttributeLabelType) {
    GBAttributeLabelTypeNormal,
    GBAttributeLabelTypeHTML,
};

@interface GBAttributedLabel : YYLabel

@property (nonatomic, copy)NSString *content;

- (instancetype)initWithType:(GBAttributeLabelType)type;

- (instancetype)initWithType:(GBAttributeLabelType)type AndContent:(NSString *)content;

@end
GBAttributedLabel.m

#import "GBAttributedLabel.h"
#import <CJRegexResult.h>
#import <RegexKitLite.h>
#define IMAGE_EXPRESSION @"<img{1}[^<|^>]+/>"
#import "CJCommon.h"
#import "ImageModel.h"
@interface GBAttributedLabel()<NSXMLParserDelegate>
@property (nonatomic, strong)NSMutableArray *regexResults;
@property (nonatomic, assign)GBAttributeLabelType type;
@property (nonatomic, strong)NSMutableArray *textArray;
@property (nonatomic, strong)NSMutableArray<ImageModel *> *imgs;
@end

@implementation GBAttributedLabel

- (NSMutableArray *)regexResults
{
    if (!_regexResults) {
        _regexResults = [NSMutableArray array];
    }
    return _regexResults;
}

- (NSMutableArray<ImageModel *> *)imgs
{
    if (!_imgs) {
        _imgs = [NSMutableArray array];
    }
    return _imgs;
}

- (instancetype)initWithType:(GBAttributeLabelType)type AndContent:(NSString *)content
{
    self = [super init];
    if (self) {

        _content = content;
        _type = type;
        [self parseContent:content];

    }
    return self;
}
- (instancetype)initWithType:(GBAttributeLabelType)type
{
    self = [super init];
    if (self) {
        _type = type;

    }
    return self;
}

- (void)parseContent:(NSString *)content
{
    self.attributedText = nil;
    [self.regexResults removeAllObjects];
    [self.imgs removeAllObjects];
    dispatch_async(dispatch_get_main_queue(), ^{
      NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] init];
        [_content enumerateStringsSeparatedByRegex:IMAGE_EXPRESSION usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
            CJRegexResult *rr = [[CJRegexResult alloc] init];
            rr.string = *capturedStrings;
            rr.range = *capturedRanges;
            [self.regexResults addObject:rr];
        }];

        for (int i = 0; i<self.regexResults.count; i++) {
            CJRegexResult * result = self.regexResults[i];
            NSString *tempStr = [NSString stringWithFormat:@"<font size='4'>%@</font>", result.string];
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithData:[tempStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
            [attributeStr appendAttributedString:attr];

            if (i != self.regexResults.count - 1) {
                CJRegexResult *result2 = self.regexResults[i + 1];
                NSString *str = [content substringWithRange:NSMakeRange(result.range.length + result.range.location, result2.range.location - (result.range.length + result.range.location))];
                NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:[str dataUsingEncoding:NSUTF8StringEncoding]];
                xmlParser.delegate = self;
                [xmlParser parse];
                ImageModel *imgModel = self.imgs[i];
                CGFloat scale = imgModel.width / imgModel.height;
                CGFloat width = [UIScreen mainScreen].bounds.size.width - 40;
                CGFloat height = (width / scale);
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
                [imageView yy_setImageWithURL:[NSURL URLWithString:imgModel.src] placeholder:[UIImage imageNamed:@"placeholder"] options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation completion:nil];
                imageView.clipsToBounds = YES;
                NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeScaleAspectFill attachmentSize:imageView.size alignToFont:Font(14) alignment:YYTextVerticalAlignmentTop];
                [attributeStr appendAttributedString:attachText];

            }
            self.attributedText = attributeStr;
            self.textVerticalAlignment = YYTextVerticalAlignmentTop;
        }
    });

}

- (void)setContent:(NSString *)content
{
    _content = content;
    [self parseContent:content];
    [self setLayout];
}

- (void)sizeToFit
{
    [super sizeToFit];
    self.textVerticalAlignment = YYTextVerticalAlignmentTop;
}

- (void)setLayout
{

}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {

    [self.imgs addObject:[ImageModel objectWithKeyValues:attributeDict]];
}

@end
控制器

- (void)viewDidLoad
{
  [super viewDidLoad];
 UIScrollView *mainScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:mainScrollView];

    UIView *contentView =  [[UIView alloc] init];
    [mainScrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(mainScrollView);
        make.left.mas_equalTo(mainScrollView.mas_left).with.offset(20);
        make.right.mas_equalTo(mainScrollView.mas_right).with.offset(-20);
        make.bottom.mas_equalTo(mainScrollView).with.offset(-10);
        make.width.mas_equalTo(self.view.width - 40);
    }];

    GBAttributedLabel *label = [[GBAttributedLabel alloc] initWithType:GBAttributeLabelTypeHTML AndContent:self.content];
   self.label = label;
    [contentView addSubview:label];
    label.preferredMaxLayoutWidth = self.view.width - 40;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.mas_equalTo(contentView);
    }];
}

- (void)viewDidAppear
{
  [super viewDidAppear];
 [self.label sizeToFit];
}

效果: 点击查看效果图

有些界面会发生这种情况,有些界面不会,不知道是不是图片的原因. 后来在真机上运行不会出现这个问题。

ibireme commented 8 years ago

如果你是用一个 Label 显示整篇内容的话,可能会在模拟器上出现问题。 模拟器不能显示超过 4096 像素的图片内容视图,真机则没问题。