[iOS开发]部分文字点击效果

在实际应用开发过程中,我们的app可能会有很多需要对部分文字选中点击的效果,比如《隐私政策》的跳转,亦或者是客服电话号码的跳转,下面我们就来学习一下如何自己去实现一个这样的功能。这里我没有使用UILabel而是使用了UITextView。因为UITextView的属性文本(attributedText)有一个超链接点击的功能(NSLinkAttributeName)。下面我们就看一下具体是如何实现的吧。

NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc]initWithString:@"温馨提示:你说是什么就是什么了"];
//获取要调整的文字位置
NSRange range = [[hintString string] rangeOfString:@"温馨提示"];
//设置链接
NSString *valueString = [[NSString stringWithFormat:@"mine://%@", @"温馨提示"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
//添加属性
[hintString addAttribute:NSLinkAttributeName value:valueString range:range];

接下来设置textView的代理,并实现响应超链接的代理方法:- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange

完整代码:

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc]initWithString:@"温馨提示:你说是什么就是什么了"];
    //获取要调整的文字位置
    NSRange range = [[hintString string] rangeOfString:@"温馨提示"];
    NSString *valueString = [[NSString stringWithFormat:@"mine://%@", @"温馨提示"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [hintString addAttribute:NSLinkAttributeName value:valueString range:range];

    UITextView *myTextView = [[UITextView alloc] initWithFrame:CGRectMake(100, 400, self.view.frame.size.width - 200, 200)];
    [self.view addSubview:myTextView];
    myTextView.editable = NO;
    myTextView.delegate = self;
    myTextView.attributedText = hintString;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    
    
    if ([[URL scheme] isEqualToString:@"mine"]) {
    
    
        NSString *titleString = [NSString stringWithFormat:@"你点击了文字:%@", URL.host];
        [self clickLinkTitle:titleString];
        return NO;
    }
    return YES;
}

- (void)clickLinkTitle:(NSString *)title {
    
    
 
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
 
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
 
    [alert addAction:action];
 
    [self presentViewController:alert animated:YES completion:nil];
}

实现效果:

在这里插入图片描述
点击温馨提示字样,会有:
在这里插入图片描述
我们简单完成了目标。

拓展

我们可以看到,默认的超链接是蓝色的纯文本,如果我们想设置其他样式,直接更改属性文本是不行的,需要这样来实现:

myTextView.linkTextAttributes = @{
    
    NSForegroundColorAttributeName : [UIColor redColor]};

此外,UITextView默认可以选中进行操作:
在这里插入图片描述
为了取消这种选中,让它和UILabel差不多,可以写一个子类,重写响应方法:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    
    
	return NO;
}

本篇文章就先介绍这么多,希望可以帮助到大家。

猜你喜欢

转载自blog.csdn.net/weixin_52192405/article/details/124862335
今日推荐