iOS开发 图文混编

图文混排3种方式

    1.webView

    优点:简单

    缺点:交互比较差,性能差

    2.textkit (使用方便)

    oc ,coretext

    3.coretext(C语言)

    优点:性能好

    缺点:使用相当复杂


viewController.m

#import "ViewController.h"
#import "TextKit.h"
#import "TextAttachs.h"

@interface ViewController () 

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpTextKit];

}

-(void)setUpTextKit{
    
    TextKit *textkit = [[TextKit alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    textkit.center = self.view.center;
    textkit.text = @"hello everyone";
    textkit.backgroundColor = [UIColor grayColor];
    [self.view addSubview:textkit];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 300, 60)];
    NSString *textStr= @"想要做自己喜欢做的事情,就必须先把不喜欢事情做好";
    // NSAttributedString 可以设置颜色,字体 背景..
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:textStr];
    NSString *str = @"自己";
    
    NSRange range = [textStr rangeOfString:str];
    // 添加属性
    [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range];
    // 添加颜色
    [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor cyanColor] range:range];
    // 设置链接
    NSString *str1 = @"必须";
    NSRange range1 = [textStr rangeOfString:str1];
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    [attribute addAttribute:NSLinkAttributeName value:url range:range1];
    
    // 设置链接的颜色
    textView.linkTextAttributes = @{
                                    NSForegroundColorAttributeName:[UIColor greenColor]
                                   };
    // 编辑状态
    textView.editable = NO;
    textView.delegate =self;

    //添加图片附件
    TextAttachs *imageAttachs = [[TextAttachs alloc] init];
    imageAttachs.image = [UIImage imageNamed:@"6.jpg"];
    // 设置属性
    NSAttributedString *attr = [NSAttributedString attributedStringWithAttachment:imageAttachs];
    [attribute insertAttributedString:attr atIndex:6];
    
    textView.attributedText = attribute;

}

#pragma mark - UITextView代理方法
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    
    return NO;
}

-(BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange{
    
    return YES;
}

iOS开发 图文混编_第1张图片

#import "TextAttachs.h"

@implementation TextAttachs

-(CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex{
    
    return CGRectMake(0, 0, 60, 60);
}


你可能感兴趣的:(图文混编)