我允许用户对NSMutableAttributedString
内的UITextView
文字进行格式化。格式化示例包括:粗体,斜体,更改字体等。
正确反映属性更改。但是,在setAttributedText
和invalidateDisplayForCharacterRange
之后,我的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];
}
答案 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 )
}
}