更改字体属性后如何使用 NSMutableAttributedString 保持 UITextview 的位置

How to maintain the position of the UITextview with NSMutableAttributedString after changing font attriibutes

我允许用户对 UITextView 中的 NSMutableAttributedString 文本进行格式化。格式示例有:粗体、斜体、更改字体等

属性更改已正确反映。但是在 setAttributedTextinvalidateDisplayForCharacterRange 之后,我的 UITextView 最终滚动到文本的最底部。如何在不改变 UITextView 位置的情况下替换文本的属性?

代码:

- (void)placeCursorAfterFormatting
{
    self.mytextview.selectedRange=currentRangeForFormatting;
}

- (IBAction)boldclicked:(UIButton *)sender {
    currentRangeForFormatting = [self.mytextview selectedRange];

    NSMutableAttributedString *atstr = [[[self.mytextview.attributedText mutableCopy] attributedSubstringFromRange:currentRangeForFormatting] mutableCopy];
    [atstr enumerateAttribute:NSFontAttributeName inRange:(NSRange){0,[atstr length]} options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
        [atstr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"AvenirNext-Bold" size:18] range:range];
    }];
    NSMutableAttributedString *atstrnew = [self.mytextview.attributedText mutableCopy];
    [atstrnew replaceCharactersInRange:currentRangeForFormatting withAttributedString:atstr];
    [self.mytextview setAttributedText:atstrnew];
    [self.mytextview.layoutManager invalidateDisplayForCharacterRange:currentRangeForFormatting];

    [self performSelector:@selector(placeCursorAfterFormatting) withObject:nil afterDelay:0.1];

}

使用

scrollRangeToVisible

示例:(对不起 Swift )

import UIKit

class ViewController: UIViewController {
    @IBOutlet   weak    var oTV :   UITextView!

    override func
    viewDidLoad() {
        super.viewDidLoad()
        oTV.attributedText = NSMutableAttributedString( string: "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda." )
    }

    @IBAction func
    boldclicked( _ : UIButton ) {
        let wRange = oTV.selectedRange
        let wAS = oTV.attributedText.mutableCopy() as! NSMutableAttributedString
        wAS.addAttribute(
            NSFontAttributeName
        ,   value: UIFont.boldSystemFont( ofSize: 20 )
        ,   range: wRange
        )
        oTV.attributedText = wAS
        oTV.layoutManager.invalidateDisplay( forCharacterRange: wRange )
        oTV.selectedRange = wRange
        oTV.scrollRangeToVisible( wRange )
    }
}