0

I am allowing the user to do formatting of the NSMutableAttributedString text inside a UITextView. Formatting examples are: Bold, Italic, Change font etc.

The attribute changes are reflected correctly. However after the setAttributedText and invalidateDisplayForCharacterRange, my UITextView ends up being scrolled to the very bottom of the text. How do I replace the attributes of the text without changing the position of the UITextView?

CODE:

- (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];

}

1 Answers1

1

Use

scrollRangeToVisible

Sample: ( sorry in 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 )
    }
}
Satachito
  • 5,838
  • 36
  • 43