突然想学学YYKit,一开始现将self.titleLb赋值了,然后再设置 yy_setTextHighlightRange ,发现点击了没有任何的反应,最后才发现,得先设置yy_setTextHighlightRange,然后再赋值给self.titleLb.
//错误代码:
#import "ViewController.h"
#import <YYText.h>
@interface ViewController ()
@property(nonatomic,strong)YYLabel * titleLb;
@end
@implementation ViewController
#pragma mark - lazy
-(YYLabel*)titleLb
{
if (!_titleLb) {
_titleLb = [YYLabel new];
_titleLb.frame = CGRectMake(10, 100, 300,40);
_titleLb.userInteractionEnabled = YES;
_titleLb.numberOfLines = 0;
_titleLb.layer.borderWidth = 1.0f;
_titleLb.textVerticalAlignment = YYTextVerticalAlignmentTop;
}
return _titleLb;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableAttributedString *text1 = [[NSMutableAttributedString alloc] initWithString:@"Some Text, blabla..."];
// 2. Set attributes to text, you can use almost all CoreText attributes.
text1.yy_font = [UIFont boldSystemFontOfSize:16];
text1.yy_color = [UIColor blueColor];
[text1 yy_setColor:[UIColor redColor] range:NSMakeRange(0, 4)];
self.titleLb.attributedText = text1;
[text1 yy_setTextHighlightRange:NSMakeRange(0, 4)//设置点击的位置
color:[UIColor redColor]
backgroundColor:[UIColor groupTableViewBackgroundColor]
tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect)
{
NSLog(@"这里是点击事件");
}];
[self.view addSubview:self.titleLb];
}
//正确代码:
#import "ViewController.h"
#import <YYText.h>
@interface ViewController ()
@property(nonatomic,strong)YYLabel * titleLb;
@end
@implementation ViewController
#pragma mark - lazy
-(YYLabel*)titleLb
{
if (!_titleLb) {
_titleLb = [YYLabel new];
_titleLb.frame = CGRectMake(10, 100, 300,40);
_titleLb.userInteractionEnabled = YES;
_titleLb.numberOfLines = 0;
_titleLb.layer.borderWidth = 1.0f;
_titleLb.textVerticalAlignment = YYTextVerticalAlignmentTop;
}
return _titleLb;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableAttributedString *text1 = [[NSMutableAttributedString alloc] initWithString:@"Some Text, blabla..."];
// 2. Set attributes to text, you can use almost all CoreText attributes.
text1.yy_font = [UIFont boldSystemFontOfSize:16];
text1.yy_color = [UIColor blueColor];
[text1 yy_setColor:[UIColor redColor] range:NSMakeRange(0, 4)];
[text1 yy_setTextHighlightRange:NSMakeRange(0, 4)//设置点击的位置
color:[UIColor redColor]
backgroundColor:[UIColor groupTableViewBackgroundColor]
tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect)
{
NSLog(@"这里是点击事件");
}];
self.titleLb.attributedText = text1;
[self.view addSubview:self.titleLb];
}