如何在更改字体attriibutes后使用NSMutableAttributedString维护UITextview的位置

时间:2016-12-08 23:04:46

标签: ios formatting uitextview nsrange nsmutableattributedstring

我允许用户对NSMutableAttributedString内的UITextView文字进行格式化。格式化示例包括:粗体,斜体,更改字体等。

正确反映属性更改。但是,在setAttributedTextinvalidateDisplayForCharacterRange之后,我的UITextView最终会滚动到文本的最底部。如何在不更改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 个答案:

答案 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 )
    }
}