使用UITextView實現文字點擊事件

原理:

採用的是UITextView的URL鏈接,設置UITextView.attributedText並設置代理delegate,響應的回調函數shouldInteractWithURL。

實現:

//使用textView的URL鏈接
    UITextView *protocolTextView = [[UITextView alloc] init];
    [_mainScrollView addSubview:protocolTextView];
    protocolTextView.backgroundColor = [UIColor clearColor];
    protocolTextView.delegate = self;
    protocolTextView.editable = NO;
    protocolTextView.scrollEnabled = NO;

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:@"我已經同意遵守閱讀《中國水泥備件網服務協議》"];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"protocol://"
                             range:[[attributedString string] rangeOfString:@"《中國水泥備件網服務協議》"]];

    protocolTextView.attributedText = attributedString;
    protocolTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor],
                                              NSUnderlineColorAttributeName: [UIColor clearColor],
                                              NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};

    [protocolTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(confirmPasswordLabel.mas_bottom).offset(30);
        make.width.mas_equalTo(280);
        make.height.mas_equalTo(30);
        make.centerX.equalTo(_mainScrollView.mas_centerX).offset(20);
    }];


#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"protocol"]) {
        RegistrationProtocolViewController *vc = [[RegistrationProtocolViewController alloc] init];
        vc.urlString = @"http://192.168.1.203:8888/Home/Login/apiDeclare";
        [self.navigationController pushViewController:vc animated:YES];
    }
    return YES;
}
發佈了63 篇原創文章 · 獲贊 98 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章