iOS富文本设置样式,插入图片,设置指定文字的点击事件


富文本:NSMutableAttributedString 它与普通文本之间最大的区别是可以设置不同字段范围的字体,颜色, 大小,样式等.

字体大小

  NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc]initWithString:@"今天的添加非常不错"];
  [attributed addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(0,3)];
字体颜色
[attributed addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3,8)];

下划线

[attributed addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(3,8)];

设置指定文字的点击事件

#import "ViewController.h"
@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:@"这是一个百度链接!!!!!"];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"baidu://"
                             range:[[attributedString string] rangeOfString:@"百度链接"]];
    
    UITextView *text = [[UITextView  alloc]init];
    text.attributedText = attributedString;
    text.frame = CGRectMake(100, 100, 300, 100);
    text.editable = NO;
    text.delegate = self;
    [self.view addSubview:text];
    
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, attributedString.length)];
    text.attributedText = attributedString;
    text.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor lightGrayColor],
                                NSUnderlineColorAttributeName: [UIColor clearColor],
                                NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};

}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"baidu"]) {
        NSLog(@"进来了");
    }
    return YES;
}
@end

点击相册图片加载到文本中

#import "ViewController.h"
#import "AppDelegate.h"
#define lkScreenWidth [UIScreen mainScreen].bounds.size.width
#define lkScreenheight [UIScreen mainScreen].bounds.size.height
#define lkTextFont 18.0
@interface ViewController ()

//内容
@property(nonatomic,strong)UITextView *content;
//图片
@property(nonatomic,strong)UIImage *picture;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"富文本";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(add)];
    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    _content= [[UITextView alloc]init];
    _content.delegate = self;
    _content.alpha = 0.8;
    _content.text = @"1234567890987654321";
    _content.font = [UIFont systemFontOfSize:lkTextFont];
    _content.textAlignment = NSTextAlignmentLeft;
    _content.layoutManager.allowsNonContiguousLayout = NO;
    _content.backgroundColor = [UIColor lightGrayColor];
    _content.frame = CGRectMake(0, 64, lkScreenWidth, lkScreenheight);
    [_content setContentSize:CGSizeMake(lkScreenWidth, lkScreenheight * 2)];
    [self.view addSubview:_content];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void) add{
    [self addPicture];
}

//选择图片
- (void) addPicture{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:@"添加图片" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *phone = [UIAlertAction actionWithTitle:@"手机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImage:UIImagePickerControllerSourceTypeCamera andPrompt:@"相机"];
        
    }];
    UIAlertAction *systemAlbum = [UIAlertAction actionWithTitle:@"从系统相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImage:UIImagePickerControllerSourceTypePhotoLibrary andPrompt:@"相册"];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertVc addAction:phone];
    [alertVc addAction:systemAlbum];
    [alertVc addAction:cancelAction];
    //如果是二次弹窗用这个不会警告
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate.window.rootViewController presentViewController:alertVc animated:YES completion:^{
    }];
}

- (void) selectImage:(UIImagePickerControllerSourceType )type andPrompt:(NSString *) prompt{
    if([UIImagePickerController isSourceTypeAvailable:type]) {
        UIImagePickerController *pickerVc = [[UIImagePickerController alloc]init];
        pickerVc.delegate = self;
        pickerVc.allowsEditing = YES;
        pickerVc.sourceType = type;
        AppDelegate *delegate = [UIApplication sharedApplication].delegate;
        [delegate.window.rootViewController presentViewController:pickerVc animated:YES completion:^{
        }];
    }else{
        NSString *str = [NSString stringWithFormat:@"请在iPhone的\"设置->隐私->%@\"选项中,允许\"xxxxx\"访问您的%@.",prompt,prompt];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"权限受限" message:str delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark  -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (!image ) {
        image = info[UIImagePickerControllerOriginalImage];
    }
    
    self.picture = image;
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithAttributedString:self.content.attributedText];
    
    [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:lkTextFont] range:NSMakeRange(0, self.content.text.length)];
    
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    attch.image = image;
    
    //大小自己调整
    attch.bounds = CGRectMake(0, 0, lkScreenWidth - 10,200);
    
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attri appendAttributedString:string];
    
    self.content.attributedText = attri;
    
    //需要重新设置下大小
    _content.font = [UIFont systemFontOfSize:lkTextFont];
    [self.content setContentSize:CGSizeMake(lkScreenWidth, lkScreenheight * 2)];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end



你可能感兴趣的:(Objective-C)