Search code examples
iosuitextviewsyntax-highlightingnsattributedstring

Syntax highlighting with attributed strings on UITextView


There is an excellent project to add syntax highlighting and line numbers to your project: https://github.com/illyabusigin/CYRTextView

But it has one critical issue described here: https://github.com/illyabusigin/CYRTextView/issues/16

The project is dead on github. Can anybody help to fix the issue? I've tried to analyze code but didn't find it yet.


Solution

  • The issue is described and fixed here: iOS 7.1 UITextView still not scrolling to cursor/caret after new line

    #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
    #define is_iOS7 SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")
    #define is_iOS8 SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")
    @implementation CYRTextView {
        ...old code...
        BOOL settingText;
    }
    
    - (id)initWithFrame:(CGRect)frame {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextViewDidChangeNotification:) name:UITextViewTextDidChangeNotification object:self];
    }
    
    - (void)scrollToCaretInTextView:(UITextView *)textView animated:(BOOL)animated {
        CGRect rect = [textView caretRectForPosition:textView.selectedTextRange.end];
        rect.size.height += textView.textContainerInset.bottom;
        [textView scrollRectToVisible:rect animated:animated];
    }
    
    - (void)handleTextViewDidChangeNotification:(NSNotification *)notification {
        if (notification.object == self && is_iOS7 && !is_iOS8 && !settingText) {
            UITextView *textView = self;
            if ([textView.text hasSuffix:@"\n"]) {
                [CATransaction setCompletionBlock:^{
                    [self scrollToCaretInTextView:textView animated:NO];
                }];
            } else {
                [self scrollToCaretInTextView:textView animated:NO];
            }
        }
    }
    
    - (void)setText:(NSString *)text {
        settingText = YES;
        ...old code...
        settingText = NO;
    }