UITextView如何在编辑时识别#号标记
2019-01-05 · 百度知道官方认证企业
解决方案:
`#import "SecondTabVC.h"
@interface SecondTabVC ()
@property (nonatomic, strong) UIScrollView *contentScrollView;//内容scrollView
@property (nonatomic, strong) UITextView *descripTextField;//描述
@property (nonatomic, assign) NSRange markRange;//标签range
@end
@implementation SecondTabVC
(void)viewDidLoad {
[super viewDidLoad];
self.title = @"SecondTab";
self.view.backgroundColor = GreenColor;self.markRange = NSMakeRange(0, 0);
self.descripTextField = [UITextView new];
self.descripTextField.delegate = self;
self.descripTextField.backgroundColor = WhiteColor;
self.descripTextField.font = Font(20);
self.descripTextField.textColor = BlackColor;
[self.view addSubview:self.descripTextField];[self.descripTextField mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(100, 0, 100, 0));
}];(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"#"]) {
NSLog(@"%@",NSStringFromRange(range));
}
return YES;
}(void)textViewDidChange:(UITextView *)textView
{
if (textView.text.length < 10) {
NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:textView.text];
[attribute addAttribute:NSForegroundColorAttributeName value:GreenColor range:NSMakeRange(0, textView.text.length - 1)];
[attribute addAttribute:NSFontAttributeName value:Font(20) range:NSMakeRange(0, textView.text.length-1)];
textView.attributedText = attribute;
}
}
}
pragma mark - UITextViewDelegate -