1. 程式人生 > >iOS富文字設定樣式,插入圖片,設定指定文字的點選事件

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 ()<UITextViewDelegate>
@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 ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

//內容
@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<UITouch *> *)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<NSString *,id> *)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


<p style="margin-top: 0px; margin-bottom: 0px; font-size: 18px; line-height: normal; font-family: Menlo; color: rgb(255, 255, 255); min-height: 21px;"><span style="font-variant-ligatures: no-common-ligatures"></span></p>