iOS UITextView 实现用户协议文字点击事件 - Objective-C 代码示例
在 iOS 的 UITextView 中,可以通过添加手势识别器来实现用户协议文字的点击事件。下面是一段使用 Objective-C 实现的示例代码:
首先,创建一个 UITextView 的子类,并添加手势识别器:
// MyTextView.h
#import <UIKit/UIKit.h>
@interface MyTextView : UITextView
@property (nonatomic, copy) void (^onLinkTapped)(NSURL *url);
@end
// MyTextView.m
#import 'MyTextView.h'
@implementation MyTextView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:tapGesture];
}
return self;
}
- (void)handleTap:(UITapGestureRecognizer *)gesture {
CGPoint tapLocation = [gesture locationInView:self];
NSTextStorage *textStorage = self.textStorage;
NSLayoutManager *layoutManager = self.layoutManager;
NSUInteger charIndex = [layoutManager characterIndexForPoint:tapLocation inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:nil];
NSRange range;
NSURL *url = [textStorage attribute:NSLinkAttributeName atIndex:charIndex effectiveRange:&range];
if (url && self.onLinkTapped) {
self.onLinkTapped(url);
}
}
@end
然后,可以在视图控制器中使用这个自定义的 UITextView,并处理点击事件:
// ViewController.m
#import 'ViewController.h'
#import 'MyTextView.h'
@interface ViewController ()
@property (nonatomic, strong) MyTextView *textView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textView = [[MyTextView alloc] initWithFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, 200)];
self.textView.editable = NO;
self.textView.dataDetectorTypes = UIDataDetectorTypeLink;
self.textView.font = [UIFont systemFontOfSize:14];
self.textView.text = '这里是用户协议,点击查看详细内容。';
self.textView.onLinkTapped = ^(NSURL *url) {
// 处理点击事件,打开链接或其他操作
NSLog(@'%@', url);
};
[self.view addSubview:self.textView];
}
@end
在这个示例中,点击用户协议中的链接文字时,会触发onLinkTapped回调,你可以在回调中处理点击事件,例如打开链接或执行其他操作。
原文地址: https://www.cveoy.top/t/topic/o8kM 著作权归作者所有。请勿转载和采集!