簡體   English   中英

將NSTextContainer / NSLayoutManager與UITextView一起使用時,文本出現亂碼

[英]Text garbled when using NSTextContainer/NSLayoutManager with UITextView

我正在實現分頁文本,因此我在使用NSLayoutManager和NSTextContainer為每個頁面創建UITextViews。 分頁工作正常,但文本顯示為亂碼。 在普通UITextView上設置相同的NSTextStorage時,它看起來是正確的:

// In the class that creates the pages
...
self.textStorage = [[NSTextStorage alloc] initWithString:string attributes:@{}];
self.layoutManager.textStorage = self.textStorage;
....

- (void)createPages{
    // Remove all current text containers
    while (self.layoutManager.textContainers.count > 0){
        [self.layoutManager removeTextContainerAtIndex:0];
    }
    NSMutableArray *textContainers = [NSMutableArray array];
    NSUInteger lastRenderedGlyph = 0;
    while (lastRenderedGlyph < self.layoutManager.numberOfGlyphs){
        NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.pageSize];
        [self.layoutManager addTextContainer:textContainer];
        [textContainers addObject:textContainer];
        [self addDummyContainersForNewlinesAfterContainer:textContainer];
        NSRange range = [self.layoutManager glyphRangeForTextContainer:textContainer];
        lastRenderedGlyph = NSMaxRange(range);
    }
    self.textContainers = textContainers;
}

// In my ViewController
- (void)addTextViews{
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.scrollView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.scrollView];
    CGFloat xOffset = 0;
    // Option #1 - This results in garbled text
    for (NSTextContainer *textContainer in self.coordinator.textContainers){
        break;
        CGRect frame = CGRectMake(xOffset, 0, self.coordinator.pageSize.width, self.coordinator.pageSize.height);
        xOffset = CGRectGetMaxX(frame)+1;
        self.scrollView.contentSize = CGSizeMake(xOffset, self.coordinator.pageSize.width);
        UITextView *textView = [[UITextView alloc] initWithFrame:frame textContainer:textContainer];
        textView.attributedText = self.coordinator.textStorage;
        [self.scrollView addSubview:textView];
    }
    // Option #2 - This does not result in garbled text
    UITextView *textView = [[UITextView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:textView];
    textView.attributedText = self.coordinator.textStorage;
}

好文字 不良文字

原來我忘了補充

    [self.textStorage addLayoutManager:self.layoutManager];

這解決了問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM