最近做了一個有關(guān)用戶勾選《用戶協(xié)議》和《隱私政策》的功能遥缕,最開始使用系統(tǒng)自帶的UItextView的富文本功能卫袒,實現(xiàn)圖文并排點擊事件,但是點擊高亮的文字和圖片后单匣,先會變灰夕凝,再進行響應事件。
折騰了半天沒有解決户秤,最后直接使用了YYLabel來實現(xiàn)這個功能码秉。
效果圖如下
步驟一:導入YYText框架
步驟二:添加代碼
//
// ViewController.m
// XXProtocol
//
// Created by Summer on 2018/6/12.
// Copyright ? 2018年 Summer. All rights reserved.
//
#import "ViewController.h"
#import "YYText.h"
@interface ViewController ()
@property (nonatomic , strong) YYLabel *yyLabel;
@property (nonatomic , assign) BOOL isSelect;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_yyLabel = [[YYLabel alloc]initWithFrame:CGRectMake(20, 100, self.view.bounds.size.width - 40, 40)];
_yyLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
_yyLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_yyLabel];
[self protocolIsSelect:NO];
}
- (void)protocolIsSelect:(BOOL)isSelect{
//設置整段字符串的顏色
UIColor *color = self.isSelect ? [UIColor blackColor] : [UIColor lightGrayColor];
NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:12], NSForegroundColorAttributeName: color};
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@" 注冊即表示同意《用戶協(xié)議》和《隱私政策》" attributes:attributes];
//設置高亮色和點擊事件
[text yy_setTextHighlightRange:[[text string] rangeOfString:@"《用戶協(xié)議》"] color:[UIColor orangeColor] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
NSLog(@"點擊了《用戶協(xié)議》");
}];
//設置高亮色和點擊事件
[text yy_setTextHighlightRange:[[text string] rangeOfString:@"《隱私政策》"] color:[UIColor orangeColor] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
NSLog(@"點擊了《隱私政策》");
}];
//添加圖片
UIImage *image = [UIImage imageNamed:self.isSelect == NO ? @"unSelectIcon" : @"selectIcon"];
NSMutableAttributedString *attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:CGSizeMake(12, 12) alignToFont:[UIFont fontWithName:@"PingFangSC-Regular" size:12] alignment:(YYTextVerticalAlignment)YYTextVerticalAlignmentCenter];
//將圖片放在最前面
[text insertAttributedString:attachment atIndex:0];
//添加圖片的點擊事件
[text yy_setTextHighlightRange:[[text string] rangeOfString:[attachment string]] color:[UIColor clearColor] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
__weak typeof(self) weakSelf = self;
weakSelf.isSelect = !weakSelf.isSelect;
[weakSelf protocolIsSelect:self.isSelect];
}];
_yyLabel.attributedText = text;
//居中顯示一定要放在這里,放在viewDidLoad不起作用
_yyLabel.textAlignment = NSTextAlignmentCenter;
}
@end
對你有用鸡号,就請給我一個贊吧????
有錯之處转砖,還請指出,感謝????