小例子首页投稿(暂停使用,暂停投稿)iOS学习开发

iOS 添加文本链接,图片

2016-07-08  本文已影响875人  去你的联盟

我们在开发过程中会遇到这样的需求。用户注册,或者做些其他操作的时候我们需要在下方加上这样一段话:注册代表你遵守我们的《用户协议》,《隐私条款》这两个是链接,那么接下来我们改怎么做呢,先上图再说话

文本链接.gif

如果我们按照平常的想法在label上面显示文字,然后给label加上手势也可以实现,那么链接多的话,你就要判断点击手势的区域,感觉麻烦,那么苹果给我们提供了很好的方法富文本NSMutableAttributedString。

 UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, 375, 100)];
    textView.backgroundColor = [UIColor cyanColor];
    //创建初始化文本的颜色,以及字体大小
    NSDictionary *dictionary = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:[UIColor yellowColor]};
    
    NSString * string = @"  跳转到百度\n\n  跳转到简书";
    //创建富文本
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:string attributes:dictionary];
    //实现文本链接
    [attributeStr addAttribute:NSLinkAttributeName value:@"http://www.jianshu.com" range:[string rangeOfString:@"简书"]];
    [attributeStr addAttribute:NSLinkAttributeName value:@"http://www.baidu.com" range:[string rangeOfString:@"百度"]];
//    textView.tintColor = [UIColor redColor];//调节文本链接字体的颜色
    
    textView.attributedText = attributeStr;
    textView.editable = NO;

上面的方法基本事件点击点解跳转的功能,当然你也可以遵守textview的delegate在

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange

    return YES;
}

代理方法里面做你想要的操作,可是呢,有时后文字是分条显示的 第一条,第二条,但是又不让用文字,而是用上面的小点图片显示的,这就需要插入图片了

 
    //文本插入图片
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"red_2"];
    //图片大小不合适 可以调整
    attachment.bounds = CGRectMake(0, 0, 8, 8);
    NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];
    //你想要插入图片的位置
    [textView.textStorage insertAttributedString:attachmentString atIndex:0];
    [textView.textStorage insertAttributedString:attachmentString atIndex:10];

富文本里面还有好多东西,有兴趣的小伙伴可以研究一下

上一篇 下一篇

猜你喜欢

热点阅读