iOS 7.1 UITextView still not scrolling to cursor/caret after new line

后端 未结 5 840
悲&欢浪女
悲&欢浪女 2020-12-04 22:25

Since iOS 7, a UITextView does not scroll automatically to the cursor as the user types text that flows to a new line. This issue is well documented on SO and e

5条回答
  •  一整个雨季
    2020-12-04 23:05

    Improved solution's code for UITextView descendant class:

    #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 MyTextView {
        BOOL settingText;
    }
    
    - (id)initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame];
        if (self) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextViewDidChangeNotification:) name:UITextViewTextDidChangeNotification object:self];
        }
        return 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;
        [super setText:text];
        settingText = NO;
    }
    

    Note it doesn't work when Down key is pressed on Bluetooth keyboard.

提交回复
热议问题