閱讀777 返回首頁    go 阿裏雲 go 技術社區[雲棲]


文字和圖片混排

文字和圖片

其實這個內容蠻早了,隻是今天整理到博客上。自從有了IOS7後,文字的顏色和文字與圖片的混排甚至把圖片作為表情都可以輕鬆地實現了。不打算書寫了,主體代碼粘貼如下,需要細看的直接下載附件就可以了。代碼下載

@interface MMTextAttachment : NSTextAttachment
{
    
}

@end

@implementation MMTextAttachment

//I want my emoticon has the same size with line's height
- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex NS_AVAILABLE_IOS(7_0)
{
    return CGRectMake( 0 , 0 , lineFrag.size.height , lineFrag.size.height );
}

@end


@interface ViewController ()

{
    UILabel *lbInfo;
    UITextView *textView;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 添加控件
     [self customizeTheLb];
    
    // 添加TextView
     [self customizeTheTextView];
    
    // 顯示不同的顏色
//    [self customizeDifferentColors];
    
    // 正則匹配,特殊顯示匹配到的文字
   // [self createRegularExpressionText];
    
    // 顯示不同的文本樣式
   // [self customizeDifferentStyles];
    
    // 取出某個區域
   // [self customizeExceptSomeZone1];
    
    
//   [self customizeExceptSomeZone2];
    
    // 圖片融入文字,作為表情
    [self customizeExceptSomeZone3];
}


- (void) customizeTheLb
{
    lbInfo = [[UILabel alloc] init];
    [self.view addSubview:lbInfo];
    lbInfo.numberOfLines = -1;
    [lbInfo setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[lbInfo]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lbInfo)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-40-[lbInfo]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lbInfo)]];
}


- (void) customizeTheTextView
{
    textView = [[UITextView alloc] init];
    [self.view addSubview:textView];
    [textView setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[textView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(textView)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[textView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(textView)]];
    
    textView.delegate = self;
    textView.selectable = NO;
    textView.text = @"wodeceshi";
}


// 顯示不同的顏色
- (void)customizeDifferentColors
{
    NSMutableString *roadInfo = [NSMutableString stringWithString:@"沿無名道路\r向楓漣山莊5號樓出發"];
    
    NSLog(@"roadInfo:%@", roadInfo);
    
    UIFont *font1 = [UIFont boldSystemFontOfSize:28];
    UIColor *textColor1 = [UIColor blackColor];
    
    UIFont *font2 = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
    UIColor *textColor2 = [UIColor colorWithRed:0.175 green:0.458 blue:0.831 alpha:1.0];
    
    NSDictionary *attrs1 = @{
                             NSForegroundColorAttributeName:textColor1,
                             NSFontAttributeName:font1
                             };
    NSRange range1 = [roadInfo rangeOfString:@"無名道路"];
    
    NSDictionary *attrs2 = @{
                            NSForegroundColorAttributeName:textColor2,
                            NSFontAttributeName:font2
                            };
    NSRange range2 = [roadInfo rangeOfString:@"楓漣山莊5號樓"];
    
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:roadInfo];
    if (range1.location != NSNotFound)
    {
        [attributedStr addAttributes:attrs1 range:range1];
    }
    if (range2.location != NSNotFound)
    {
        [attributedStr addAttributes:attrs2 range:range2];
    }
    lbInfo.attributedText = attributedStr;
    
    
    lbInfo.preferredMaxLayoutWidth = 200;
    lbInfo.backgroundColor = [UIColor yellowColor];
    CGSize size = [lbInfo systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    NSLog(@"--height:%f", size.height);
}



- (void) createRegularExpressionText
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"孫某人" options:0 error:Nil];
    NSMutableString *regularInfo = [NSMutableString stringWithString:@"這個測試孫某人信息顯示正確與否--孫某人"];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:regularInfo];
    NSRange searchRange = NSMakeRange(0, regularInfo.length);
    
    UIFont *font = [UIFont boldSystemFontOfSize:18];
    UIColor *textColor = [UIColor blueColor];
    
    NSDictionary *attrs = @{
                             NSForegroundColorAttributeName:textColor,
                             NSFontAttributeName:font
                             };
    
    [regex enumerateMatchesInString:regularInfo options:0 range:searchRange usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
        NSRange matchRange = [match rangeAtIndex:0];
        [attributedStr addAttributes:attrs range:matchRange];
    }];
    
    lbInfo.attributedText = attributedStr;
}


// 文本顯示不同的樣式
- (void) customizeDifferentStyles
{
    NSMutableString *roadInfo = [NSMutableString stringWithString:@"關於農村宅基地改革的問題,目前確實有一個試點方案,已經編製完成了,但還沒有最後批準。”23日上午,一位不願具名的國土資源部內部人士向記者證實,國土資源部已經初步編製完成了農村宅基地製度改革試點方案www.baidu.com。\r所謂農村宅基地,是農村的農戶或個人用作住宅基地而占有、利用本集體所有的土地。包括已經建設房屋、建過房屋或者決定用於建造房屋的土地,已經建設房屋的土地、建過房屋但已無上蓋物或不能居住的土地以及準備建房用的規劃地三種類型。\r據悉,按照目前已經基本成型的“試點方案”,農村宅基地改革試點工作將按照“分類處理”原則的進行。所謂分類,即“城鄉建設用地擴展邊界外的傳統農區”和“城鄉建設用地擴展邊界內”兩類,對於這兩類不同情況,將以不同方式貫徹“一戶一宅”的原則。"];
    
    UIFont *font = [UIFont systemFontOfSize:18];
    UIColor *textColor = [UIColor blackColor];
    NSMutableParagraphStyle *parahStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    parahStyle.firstLineHeadIndent =20;
   // parahStyle.headIndent = 20;
   // parahStyle.tailIndent = 10;
   // parahStyle.lineSpacing = 90;
   // parahStyle.paragraphSpacing = 20;
   // parahStyle.paragraphSpacingBefore = 80;
    
    
    NSDictionary *attrs = @{
                             NSForegroundColorAttributeName:textColor,
                             NSFontAttributeName:font,
                             NSParagraphStyleAttributeName:parahStyle,
                             NSKernAttributeName:@10,
                            // NSUnderlineStyleAttributeName:@1,
                            // NSStrokeWidthAttributeName:@2
                             };
    NSRange range = NSMakeRange(0, roadInfo.length);
    
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:roadInfo];
    [attributedStr addAttributes:attrs range:range];
    
    [attributedStr addAttribute:NSLinkAttributeName
                             value:@"link1://www.baidu.com"
                             range:[roadInfo rangeOfString:@"www.baidu.com"]];
    
    NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],
                                     NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                     NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
    
    textView.linkTextAttributes = linkAttributes;
    textView.delegate = self;
    textView.editable = NO;
    textView.selectable = YES;
    
    textView.attributedText = attributedStr;
}


- (void)textViewDidBeginEditing:(UITextView *)textView
{
    
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    
    
    return YES;
}


/*
- (BOOL) textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([URL.scheme isEqualToString:@"link1"])
    {
        NSLog(@"點擊進入百度網站");
        
        return NO;
    }
    
    return YES;
}
*/


- (void) customizeExceptSomeZone1
{
    CGRect rect = CGRectMake(100, 100, 100, 100);
    
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.frame = rect;
    imageV.image = [UIImage imageNamed:@"xiang.png"];
    
    imageV.layer.masksToBounds = YES;
    imageV.layer.cornerRadius = CGRectGetWidth(imageV.frame) / 2.0;
    [textView addSubview:imageV];
    
    
    NSMutableString *roadInfo = [NSMutableString stringWithString:@"關於農村宅基地改革的問題,目前確實有一個試點方案,已經編製完成了,但還沒有最後批準。”23日上午,一位不願具名的國土資源部內部人士向記者證實,國土資源部已經初步編製完成了農村宅基地製度改革試點方案www.baidu.com。\r所謂農村宅基地,是農村的農戶或個人用作住宅基地而占有、利用本集體所有的土地。包括已經建設房屋、建過房屋或者決定用於建造房屋的土地,已經建設房屋的土地、建過房屋但已無上蓋物或不能居住的土地以及準備建房用的規劃地三種類型。\r據悉,按照目前已經基本成型的“試點方案”,農村宅基地改革試點工作將按照“分類處理”原則的進行。所謂分類,即“城鄉建設用地擴展邊界外的傳統農區”和“城鄉建設用地擴展邊界內”兩類,對於這兩類不同情況,將以不同方式貫徹“一戶一宅”的原則。"];
    textView.text = roadInfo;
    textView.font = [UIFont systemFontOfSize:18];
    
    UIBezierPath *newPath = [UIBezierPath bezierPathWithOvalInRect:imageV.frame];
 //   UIBezierPath *newPath = [UIBezierPath bezierPathWithRect:imageV.frame];
    textView.textContainer.exclusionPaths = @[newPath];
    
}


- (void) customizeExceptSomeZone2
{
    CGRect rect = CGRectMake(0, 0, 40, 40);
    NSTextAttachment * textAttachment = [[ NSTextAttachment alloc ] initWithData:nil ofType:nil ] ;
    UIImage * smileImage = [ UIImage imageNamed:@"xiang.png" ]  ;  //my emoticon image named a.jpg
    textAttachment.image = smileImage;
    textAttachment.bounds = rect;
    
    
    NSMutableString *roadInfo = [NSMutableString stringWithString:@"關於農村宅基地改革的問題,目前確實有一個試點方案,已經編製完成了,但還沒有最後批準。”23日上午,一位不願具名的國土資源部內部人士向記者證實,國土資源部已經初步編製完成了農村宅基地製度改革試點方案www.baidu.com。\r所謂農村宅基地,是農村的農戶或個人用作住宅基地而占有、利用本集體所有的土地。包括已經建設房屋、建過房屋或者決定用於建造房屋的土地,已經建設房屋的土地、建過房屋但已無上蓋物或不能居住的土地以及準備建房用的規劃地三種類型。\r據悉,按照目前已經基本成型的“試點方案”,農村宅基地改革試點工作將按照“分類處理”原則的進行。所謂分類,即“城鄉建設用地擴展邊界外的傳統農區”和“城鄉建設用地擴展邊界內”兩類,對於這兩類不同情況,將以不同方式貫徹“一戶一宅”的原則。"];
    textView.text = roadInfo;
    
    NSDictionary *attrs = @{
                            NSFontAttributeName:[UIFont systemFontOfSize:18]
                            };
    
    NSMutableAttributedString * string = [[ NSMutableAttributedString alloc ] initWithString:roadInfo  attributes:attrs ] ;
    
    NSAttributedString * textAttachmentString = [ NSAttributedString attributedStringWithAttachment:textAttachment ] ;
    [ string insertAttributedString:textAttachmentString atIndex:20] ;
    
    textView.attributedText = string ;
}


// 作為文字表情,與文字大小一樣,融入文字
- (void) customizeExceptSomeZone3
{
    MMTextAttachment* textAttachment = [[ MMTextAttachment alloc ] initWithData:nil ofType:nil ] ;
    UIImage * smileImage = [ UIImage imageNamed:@"xiang.png" ]  ;  //my emoticon image named a.jpg
    textAttachment.image = smileImage;
    
    
    NSMutableString *roadInfo = [NSMutableString stringWithString:@"關於農村宅基地改革的問題,目前確實有一個試點方案,已經編製完成了,但還沒有最後批準。”23日上午,一位不願具名的國土資源部內部人士向記者證實,國土資源部已經初步編製完成了農村宅基地製度改革試點方案www.baidu.com。\r所謂農村宅基地,是農村的農戶或個人用作住宅基地而占有、利用本集體所有的土地。包括已經建設房屋、建過房屋或者決定用於建造房屋的土地,已經建設房屋的土地、建過房屋但已無上蓋物或不能居住的土地以及準備建房用的規劃地三種類型。\r據悉,按照目前已經基本成型的“試點方案”,農村宅基地改革試點工作將按照“分類處理”原則的進行。所謂分類,即“城鄉建設用地擴展邊界外的傳統農區”和“城鄉建設用地擴展邊界內”兩類,對於這兩類不同情況,將以不同方式貫徹“一戶一宅”的原則。"];
    textView.text = roadInfo;
    
    NSDictionary *attrs = @{
                            NSFontAttributeName:[UIFont systemFontOfSize:18]
                            };
    
    NSMutableAttributedString * string = [[ NSMutableAttributedString alloc ] initWithString:roadInfo  attributes:attrs ] ;
    
    NSAttributedString * textAttachmentString = [ NSAttributedString attributedStringWithAttachment:textAttachment ] ;
    [ string insertAttributedString:textAttachmentString atIndex:20] ;
    
    textView.attributedText = string ;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

最後更新:2017-07-15 22:32:22

  上一篇:go  阿裏雲推薦碼2017卷土重來--雲大使Cotyun.cn分享7月份可用的阿裏雲八折推薦碼
  下一篇:go  Eclipse中如何clean項目以及clean的作用