UILabel部分文字可点击
源代码:https://github.com/lyb5834/YBAttributeTextTapAction地址
如果想用富文本文件,可以参考的另外一篇博客;
https://www.cnblogs.com/hualuoshuijia/p/5732619.html
如果只需要做点击,只需要使用一个类别文件就可以
#import <UIKit/UIKit.h> @protocol RichTextDelegate <NSObject>
@optional
/**
* RichTextDelegate
*
* @param string 点击的字符串
* @param range 点击的字符串range
* @param index 点击的字符在数组中的index
*/
- (void)didClickRichText:(NSString *)string
range:(NSRange)range
index:(NSInteger)index;
@end @interface UILabel (RichText) /**
* 是否打开点击效果,默认是打开
*/
@property (nonatomic, assign) BOOL enabledClickEffect; /**
* 点击效果颜色 默认lightGrayColor
*/
@property (nonatomic, strong) UIColor *clickEffectColor; /**
* 给文本添加Block点击事件回调
*
* @param strings 需要添加的字符串数组
* @param clickAction 点击事件回调
*/
- (void)clickRichTextWithStrings:(NSArray <NSString *> *)strings
clickAction:(void (^) (NSString *string, NSRange range, NSInteger index))clickAction; /**
* 给文本添加点击事件delegate回调
*
* @param strings 需要添加的字符串数组
* @param delegate 富文本代理
*/
- (void)clickRichTextWithStrings:(NSArray <NSString *> *)strings
delegate:(id <RichTextDelegate> )delegate;
#import "UILabel+RichText.h"
#import <objc/runtime.h>
#import <CoreText/CoreText.h>
#import <Foundation/Foundation.h> #define weakSelf(type) __weak typeof(type) weak##type = type; @interface RichTextModel : NSObject @property (nonatomic, copy) NSString *str; @property (nonatomic, assign) NSRange range; @end @implementation RichTextModel @end @implementation UILabel (RichText) #pragma mark - AssociatedObjects - (NSMutableArray *)attributeStrings { return objc_getAssociatedObject(self, _cmd);
} - (void)setAttributeStrings:(NSMutableArray *)attributeStrings { objc_setAssociatedObject(self, @selector(attributeStrings), attributeStrings, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} - (NSMutableDictionary *)effectDic { return objc_getAssociatedObject(self, _cmd);
} - (void)setEffectDic:(NSMutableDictionary *)effectDic { objc_setAssociatedObject(self, @selector(effectDic), effectDic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} - (BOOL)isClickAction { return [objc_getAssociatedObject(self, _cmd) boolValue];
} - (void)setIsClickAction:(BOOL)isClickAction { objc_setAssociatedObject(self, @selector(isClickAction), @(isClickAction), OBJC_ASSOCIATION_ASSIGN);
} - (void (^)(NSString *, NSRange, NSInteger))clickBlock { return objc_getAssociatedObject(self, _cmd);
} - (void)setClickBlock:(void (^)(NSString *, NSRange, NSInteger))clickBlock { objc_setAssociatedObject(self, @selector(clickBlock), clickBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
} - (id<RichTextDelegate>)delegate { return objc_getAssociatedObject(self, _cmd);
} - (BOOL)enabledClickEffect { return [objc_getAssociatedObject(self, _cmd) boolValue];
} - (void)setEnabledClickEffect:(BOOL)enabledClickEffect { objc_setAssociatedObject(self, @selector(enabledClickEffect), @(enabledClickEffect), OBJC_ASSOCIATION_ASSIGN);
// self.isClickEffect = enabledClickEffect;
} - (UIColor *)clickEffectColor { UIColor *obj = objc_getAssociatedObject(self, _cmd);
if(obj == nil) {obj = [UIColor lightGrayColor];}
return obj;
} - (void)setClickEffectColor:(UIColor *)clickEffectColor { objc_setAssociatedObject(self, @selector(clickEffectColor), clickEffectColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} - (BOOL)isClickEffect { return [objc_getAssociatedObject(self, _cmd) boolValue];
} - (void)setIsClickEffect:(BOOL)isClickEffect { objc_setAssociatedObject(self, @selector(isClickEffect), @(isClickEffect), OBJC_ASSOCIATION_ASSIGN);
} - (void)setDelegate:(id<RichTextDelegate>)delegate { objc_setAssociatedObject(self, @selector(delegate), delegate, OBJC_ASSOCIATION_ASSIGN);
} #pragma mark - mainFunction
- (void)clickRichTextWithStrings:(NSArray<NSString *> *)strings clickAction:(void (^)(NSString *, NSRange, NSInteger))clickAction { [self richTextRangesWithStrings:strings]; if (self.clickBlock != clickAction) {
self.clickBlock = clickAction;
}
} - (void)clickRichTextWithStrings:(NSArray<NSString *> *)strings delegate:(id<RichTextDelegate>)delegate { [self richTextRangesWithStrings:strings]; if ([self delegate] != delegate) { [self setDelegate:delegate];
}
} #pragma mark - touchAction
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if (!self.isClickAction) {
return;
} if (objc_getAssociatedObject(self, @selector(enabledClickEffect))) {
self.isClickEffect = self.enabledClickEffect;
} UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; weakSelf(self);
[self richTextFrameWithTouchPoint:point result:^(NSString *string, NSRange range, NSInteger index) { if (weakself.clickBlock) {
weakself.clickBlock (string , range , index);
} if ([weakself delegate] && [[weakself delegate] respondsToSelector:@selector(didClickRichText:range:index:)]) {
[[weakself delegate] didClickRichText:string range:range index:index];
} if (weakself.isClickEffect) { [weakself saveEffectDicWithRange:range]; [weakself clickEffectWithStatus:YES];
}
}];
} - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { if((self.isClickAction) && ([self richTextFrameWithTouchPoint:point result:nil])) { return self;
}
return [super hitTest:point withEvent:event];
} #pragma mark - getClickFrame
- (BOOL)richTextFrameWithTouchPoint:(CGPoint)point result:(void (^) (NSString *string , NSRange range , NSInteger index))resultBlock
{
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self.attributedText); CGMutablePathRef Path = CGPathCreateMutable(); CGPathAddRect(Path, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL); CFRange range = CTFrameGetVisibleStringRange(frame); if (self.attributedText.length > range.length) { UIFont *font ; if ([self.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil]) { font = [self.attributedText attribute:NSFontAttributeName atIndex:0 effectiveRange:nil]; }else if (self.font){
font = self.font; }else {
font = [UIFont systemFontOfSize:17];
} CGPathRelease(Path); Path = CGPathCreateMutable(); CGPathAddRect(Path, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height + font.lineHeight)); frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);
} CFArrayRef lines = CTFrameGetLines(frame); if (!lines) {
CFRelease(frame);
CFRelease(framesetter);
CGPathRelease(Path);
return NO;
} CFIndex count = CFArrayGetCount(lines); CGPoint origins[count]; CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins); CGAffineTransform transform = [self transformForCoreText]; CGFloat verticalOffset = 0; for (CFIndex i = 0; i < count; i++) {
CGPoint linePoint = origins[i]; CTLineRef line = CFArrayGetValueAtIndex(lines, i); CGRect flippedRect = [self getLineBounds:line point:linePoint]; CGRect rect = CGRectApplyAffineTransform(flippedRect, transform); rect = CGRectInset(rect, 0, 0); rect = CGRectOffset(rect, 0, verticalOffset); NSParagraphStyle *style = [self.attributedText attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:nil]; CGFloat lineSpace; if (style) {
lineSpace = style.lineSpacing;
}else {
lineSpace = 0;
} CGFloat lineOutSpace = (self.bounds.size.height - lineSpace * (count - 1) -rect.size.height * count) / 2; rect.origin.y = lineOutSpace + rect.size.height * i + lineSpace * i; if (CGRectContainsPoint(rect, point)) { CGPoint relativePoint = CGPointMake(point.x - CGRectGetMinX(rect), point.y - CGRectGetMinY(rect)); CFIndex index = CTLineGetStringIndexForPosition(line, relativePoint); CGFloat offset; CTLineGetOffsetForStringIndex(line, index, &offset); if (offset > relativePoint.x) {
index = index - 1;
} NSInteger link_count = self.attributeStrings.count; for (int j = 0; j < link_count; j++) { RichTextModel *model = self.attributeStrings[j]; NSRange link_range = model.range;
if (NSLocationInRange(index, link_range)) {
if (resultBlock) {
resultBlock (model.str , model.range , (NSInteger)j);
}
CFRelease(frame);
CFRelease(framesetter);
CGPathRelease(Path);
return YES;
}
}
}
}
CFRelease(frame);
CFRelease(framesetter);
CGPathRelease(Path);
return NO;
} - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if (self.isClickEffect) { [self performSelectorOnMainThread:@selector(clickEffectWithStatus:) withObject:nil waitUntilDone:NO];
}
} - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if (self.isClickEffect) { [self performSelectorOnMainThread:@selector(clickEffectWithStatus:) withObject:nil waitUntilDone:NO];
}
} - (CGAffineTransform)transformForCoreText
{
return CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f);
} - (CGRect)getLineBounds:(CTLineRef)line point:(CGPoint)point
{
CGFloat ascent = 0.0f;
CGFloat descent = 0.0f;
CGFloat leading = 0.0f;
CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CGFloat height = ascent + fabs(descent) + leading; return CGRectMake(point.x, point.y , width, height);
} #pragma mark - clickEffect
- (void)clickEffectWithStatus:(BOOL)status
{
if (self.isClickEffect) {
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText]; NSMutableAttributedString *subAtt = [[NSMutableAttributedString alloc] initWithAttributedString:[[self.effectDic allValues] firstObject]]; NSRange range = NSRangeFromString([[self.effectDic allKeys] firstObject]); if (status) {
[subAtt addAttribute:NSBackgroundColorAttributeName value:self.clickEffectColor range:NSMakeRange(0, subAtt.string.length)]; [attStr replaceCharactersInRange:range withAttributedString:subAtt];
}else { [attStr replaceCharactersInRange:range withAttributedString:subAtt];
}
self.attributedText = attStr;
}
} - (void)saveEffectDicWithRange:(NSRange)range
{
self.effectDic = [NSMutableDictionary dictionary]; NSAttributedString *subAttribute = [self.attributedText attributedSubstringFromRange:range]; [self.effectDic setObject:subAttribute forKey:NSStringFromRange(range)];
} #pragma mark - getRange
- (void)richTextRangesWithStrings:(NSArray <NSString *> *)strings
{
if (self.attributedText == nil) {
self.isClickAction = NO;
return;
} self.isClickAction = YES; self.isClickEffect = YES; __block NSString *totalStr = self.attributedText.string; self.attributeStrings = [NSMutableArray array]; weakSelf(self);
[strings enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { NSRange range = [totalStr rangeOfString:obj]; if (range.length != 0) { totalStr = [totalStr stringByReplacingCharactersInRange:range withString:[weakself getStringWithRange:range]]; RichTextModel *model = [[RichTextModel alloc]init]; model.range = range; model.str = obj; [weakself.attributeStrings addObject:model];
}
}];
} - (NSString *)getStringWithRange:(NSRange)range
{
NSMutableString *string = [NSMutableString string]; for (int i = 0; i < range.length ; i++) { [string appendString:@" "];
}
return string;
} @end
使用方法:
NSString *text = @"池塘大桥下,游过一群鸭池塘,快来快来数一数,二四六七八,嘎嘎嘎嘎,真呀真多呀,fly,数不清到底多少鸭";
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:text];
[string addAttribute:action1 value:@"" range:NSMakeRange(2, 3)];
[string addAttributes:@{NSStrikethroughStyleAttributeName:@"",NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(2, 3)];
self.label2.userInteractionEnabled = true;
self.label2.attributedText = string;
// self.label2.enabledClickEffect = false;
[self.label2 clickRichTextWithStrings:@[@"池塘"] clickAction:^(NSString *string, NSRange range, NSInteger index) {
NSLog(@"-------");
}];
如果想用富文本文件,可以参考的另外一篇博客;
https://www.cnblogs.com/hualuoshuijia/p/5732619.html
UILabel部分文字可点击的更多相关文章
- iOS开发小技巧 - label中的文字添加点击事件
Label中的文字添加点击事件 GitHub地址:https://github.com/lyb5834/YBAttributeTextTapAction 以前老师讲过类似的功能,自己懒得回头看了,找了 ...
- 浅谈ClickableSpan , 实现TextView文本某一部分文字的点击响应
超文本:http://www.baidu.com 这么一个效果:一行文本当中 前面显示黑色颜色的“超文本:”,后面显示红色颜色的“http://www.baidu.com” 并且要求红色字体的部分可以 ...
- IOS UI篇—UILabel的文字顶部对齐
UILabel的文字顶部对齐 NOV 20TH, 2011 默认UILabel是垂直居中对齐的,如果你的UILabel高度有多行,当内容少的时候,会自动垂直居中. 如下图所示(图片来自stackove ...
- TextView中的部分文字响应点击事件
TextView是android常用的控件,经常要显示不同文字的大小,颜色,......今天要实现这样这样一个需求,TextView某段内容显示的文字颜色不一样,并且点击区域只能是改变了颜色的字. 1 ...
- 设置UIButton或者UILabel显示文字的行数
需要在UIButton的titleLabel或者UILabel的text 字符串里面添加换行符号 “\n”,并且设置 UILabel的numberOfLines属性 栗子:行数要和“\n”的个数对应, ...
- 让UILabel的文字顶部对齐
参考资料 http://stackoverflow.com/questions/1054558/how-do-i-vertically-align-text-within-a-uilabel 方法一 ...
- ios7之后 根据UILabel的文字计算frame的方法
ios7 新出来的根据label的文字和字体大小来确定label的宽高. 官方的方法是: - (CGRect)boundingRectWithSize:(CGSize)size options:(NS ...
- TextView部分文字可点击跳转
效果图: 需求:每个item的文字都有两部分是连接可点击 当然需要用到SpannableString和ClickableSpan. import android.text.TextPaint; imp ...
- 富文本 文字图片点击,(TextView)
textview上的富文本支持 文字,图片的点击事件 - (void)protocolIsSelect:(BOOL)select { NSMutableAttributedString *attrib ...
随机推荐
- 为什么V8引擎这么快?[转]
转载请注明出处:http://blog.csdn.net/horkychen Google研发的V8 JavaScript引擎性能优异.我们请熟悉内部程序实现的作者依源代码来看看V8是如何加速的. 作 ...
- Golang Gin 框架 Route备注
https://www.jianshu.com/p/d4b52187d233 https://blog.csdn.net/weixin_34210740/article/details/8602756 ...
- Java Debugging with Eclipse - Tutorial
1.1. What is debugging? Debugging allows you to run a program interactively while watching the sourc ...
- 5.STM32通用定时器TIM3中断
1.通用定时器TIM3中断 #include "timer.h" #include "led.h" void TIM3_Int_Init(u16 arr,u16 ...
- 10.13 Django随笔
2018-10-13 14:20:59 越努力,越幸运! 永远不要高估自己! Django的渲染是在render()时候渲染的,然后把字符串传给浏览器 Django请求流程, 跨域 参考链接: htt ...
- WebApi路由
路由分为两种模式:模板路由和特性路由. 模板路由: 模板路由是ASP.NET Web API默认提供的路由.模板路由使用前需要定义路由模板.如下面默认的路由模板: 默认路由的URL格式是api/{co ...
- 网络通信协议之ICMP
ICMP(互联网控制消息协议) ICMP >>Internet Control Message Protocol IP协议的缺点: >>无差错报告和差错纠正机制 >> ...
- .NET Core开发日志——Action
在叙述Controller一文中,有一处未做解释,即CreateControllerFactory方法中ControllerActionDescriptor参数是如何产生的.这是因为其与Action的 ...
- web 框架的本质及自定义web框架 模板渲染jinja2 mvc 和 mtv框架 Django框架的下载安装 基于Django实现的一个简单示例
Django基础一之web框架的本质 本节目录 一 web框架的本质及自定义web框架 二 模板渲染JinJa2 三 MVC和MTV框架 四 Django的下载安装 五 基于Django实现的一个简单 ...
- c语言之要点-泛篇
1.goto goto由goto和标签名组成, 1 1 if(....) 2 2 { 3 3 ..... 4 4 goto part2; 5 5 } 6 6 part2: printf(". ...