实现类似微博@..的点击文字跳转事件 iOS

来源:互联网 发布:广告投放算法 编辑:程序博客网 时间:2024/04/30 05:38

#import "firstVC.h"

#import "secondVC.h"

#import "userlist.h"


@interface firstVC ()<UITextViewDelegate>


@end


@implementation firstVC


{

    NSMutableAttributedString *_attributedString;

    NSArray * _dataArr;

}


- (void)viewDidLoad {

    [superviewDidLoad];

//    给定一个用户列表

    _dataArr =@[@"nonono",@"abc"];

    

}




-(void)createTextView{

    

    UITextView * TView = [[UITextViewalloc]initWithFrame:CGRectMake(100,100,200,100)];

    

    TView.backgroundColor = [UIColorlightGrayColor];

    

    TView.editable =NO;

//创建富文本

    _attributedString = [[NSMutableAttributedStringalloc]initWithString:self.textviewCS.text];

    

    

    for (NSString * resstrin_dataArr) {

        //遍历是否存在相同字符串

        if ([self.textviewCS.textrangeOfString:resstr].location!=NSNotFound) {

    

//            发现相同的关键字

        NSString * usernameCS = resstr;

            

        NSString * totalname = [NSStringstringWithFormat:@"@%@",usernameCS];

//添加链接的方式

        [_attributedStringaddAttribute:NSLinkAttributeName

                             value:[NSStringstringWithFormat:@"username://%@",usernameCS]

                             range:[[_attributedStringstring]rangeOfString:[NSStringstringWithFormat:@"%@",totalname]]];

//    设置点击时的样式

        NSDictionary *linkAttributes =@{NSForegroundColorAttributeName: [UIColorgreenColor],NSUnderlineColorAttributeName: [UIColorlightGrayColor],NSUnderlineStyleAttributeName:@(NSUnderlinePatternSolid)};

//    添加链接文字

        TView.linkTextAttributes = linkAttributes;


        }

    }

    

        TView.attributedText =_attributedString;

    

        TView.delegate =self;

    

    [self.viewaddSubview:TView];

}



//点击的回调

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

    

    if ([[URLscheme]isEqualToString:@"username"]) {

//        自定义的点击文字

        NSString *username = [URLhost];

        

        NSLog(@"%@",username);

        

        secondVC * VC = [[secondVCalloc]init];

        

        [self.navigationControllerpushViewController:VCanimated:YES];

        

        VC.title= username;

        

        returnNO;

        

    }

    

    returnYES;


}


//发布

- (IBAction)push:(UIButton *)sender {

    

    [selfcreateTextView];

    

}

//跳转用户列表

- (IBAction)jumpUser:(UIButton *)sender {

    

    userlist * userVC = [[userlistalloc]init];

    

    [self.navigationControllerpushViewController:userVCanimated:YES];

    

    userVC.dataArr=_dataArr;

    

    

}

@end

0 0
原创粉丝点击