简体   繁体   中英

Incorrect scrolling UITextView with NSAttributedString

I want to make a synchronized show lyric app and all lyric shown on a UITextView . In order to highlight current lyric I add background color to NSAttributedString of UITextView . All NSRange of lines stored in a NSArray .

My code is pretty simple, when button tapped move the highlight line down (via set contentOffset of UITextView). But here a strange problem occurred. In the beginning, the UITextView scroll properly but when contentOffset of UITextView greater then its frame.size.height it was fixed.

Here is my code:

//View controller
#import "ViewController.h"

@interface ViewController () {
    NSUInteger globelIndex;
    NSArray *textRanges;
    NSMutableAttributedString *attributedText;
}

@property (weak, nonatomic) IBOutlet UITextView *lyricView;
@property (strong, nonatomic) NSTimer *mainTimer;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *rawText = [self readFile];
    globelIndex = 0;
    [self initTextLines:rawText];
    attributedText = [[NSMutableAttributedString alloc] initWithString:rawText
                                                            attributes:@{NSBackgroundColorAttributeName: [UIColor orangeColor]}];

    self.lyricView.attributedText = [attributedText copy];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)manualNextLine:(UIButton *)sender {
    [self updateTextView];
}

- (IBAction)autoNextLineUsingNSTimer:(UIButton *)sender {
    self.mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTextView) userInfo:nil repeats:YES];
}

- (void)updateTextView {
    if (self.lyricView.contentOffset.y >= self.lyricView.contentSize.height &&
        self.mainTimer)
    {
        self.mainTimer = nil;
        return;
    }

    NSMutableAttributedString *mat = [attributedText mutableCopy];
    NSValue *value = [textRanges objectAtIndex:globelIndex];
    [mat addAttribute:NSBackgroundColorAttributeName value:[UIColor whiteColor] range:[value rangeValue]];

    self.lyricView.attributedText = [mat copy];

    globelIndex += 1;

    //    self.textView.contentOffset = CGPointMake(self.textView.contentOffset.x, self.textView.contentOffset.y + 24);

    //    [self.textView scrollRangeToVisible:[value rangeValue]];
    CGPoint newOffset = CGPointMake(self.lyricView.contentOffset.x, self.lyricView.contentOffset.y + 20);
    [self.lyricView setContentOffset:newOffset animated:NO];

    NSLog(@"[%@ %@] h: %f b: %f a: %f", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.lyricView.contentSize.height, newOffset.y, self.lyricView.contentOffset.y);
}

#pragma mark - helper

- (void)initTextLines:(NSString *)rawText {
    NSMutableArray *result = [@[] mutableCopy];
    NSArray *t = [rawText componentsSeparatedByString:@"\r\n"];
    __block int index = 0;

    [t enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *s = obj;
        NSRange range = NSMakeRange(index, s.length + 2);
        [result addObject:[NSValue valueWithRange:range]];
        index += s.length + 2;
    }];


    textRanges = [result copy];
}

- (NSString *)readFile {
    NSError *error = nil;
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"二人の季節が-ささきのぞみ-想い" withExtension:@"lrc"];
    NSString *content = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        if (DEBUG) NSLog(@"[%@ %@] Error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
        abort();
    }
    return content;
}

@end

All my code was in ViewController and StoryBoard has two UIButton and a UITextView. What I wonder is "Why the UITextView.contentOffset cannot change when it greater than some size".

Maybe rewrite setContentOffset:animated is helpful for you!

Here is some sample code which you can borrow:
https://github.com/360/Three20/blob/master/src/Three20UI/Sources/TTTextView.m

#import "Three20UI/TTTextView.h"

// UI
#import "Three20UI/UIViewAdditions.h"

@implementation TTTextView

@synthesize autoresizesToText = _autoresizesToText;
@synthesize overflowed        = _overflowed;

- (void)setContentOffset:(CGPoint)offset animated:(BOOL)animated {
  if (_autoresizesToText) {
    if (!_overflowed) {
      // In autosizing mode, we don't ever allow the text view to scroll past zero
      // unless it has past its maximum number of lines
      [super setContentOffset:CGPointZero animated:animated];

    } else {
      // If there is an overflow, we force the text view to keep the cursor at the bottom of the
      // view.
      [super setContentOffset: CGPointMake(offset.x, self.contentSize.height - self.height)
                     animated: animated];
    }

  } else {
    [super setContentOffset:offset animated:animated];
  }
}


@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM