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