NSTextContainer、NSLayoutManager、NSTextStorage
является новым для iOS7:
1) NSTextContainer:
NSTextContainer класс определяет область, в которой текст выложен. Объект NSTextContainer определяет прямоугольные области, и вы можете определить пути исключения в тексте контейнера, входящего в прямоугольник, в виде потока, связанного с отображением пути.
2) NSLayoutManager:
NSLayoutManager координаты объекта расположение и отображение символов, проведенных в объекте NSTextStorage. Он отображает коды символов Unicode на глифы, устанавливает глифы в серии объектов NSTextContainer и отображает их в виде нескольких объектов текстового вида.
3) NSTextStorage:
NSTextStorage является semiconcrete подкласс NSMutableAttributedString, который управляет набором клиентских NSLayoutManagerobjects, notifyingthemofanychangestoitscharactersorattributessothattheycanrelay и снова отобразить текст по мере необходимости.
Мы могли бы знать, NSTextStorage
может хранить и управлять UITextView
«s текст, и это NSMutableAttributedString
» s subclass.We может добавить или изменить атрибуты, так что это хороший выбор, чтобы хранить и управлять UITextView
«s текст.
NSLayoutManager
использование для управления контентом NSTextStorage
.
NSTextContainer
предоставить прямоугольник, чтобы зачеркнуть текст.
Мы можем просто использовать их:
CGRect textViewRect = CGRectInset(self.view.bounds, 10.0, 20.0);
// NSTextContainer
NSTextContainer *container = [[NSTextContainer alloc] initWithSize:CGSizeMake(textViewRect.size.width, CGFLOAT_MAX)]; // new in iOS 7.0
container.widthTracksTextView = YES; // Controls whether the receiveradjusts the width of its bounding rectangle when its text view is resized
// NSLayoutManager
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; // new in iOS 7.0
[layoutManager addTextContainer:container];
// NSTextStorage subclass
self.textStorage = [[TextStorage alloc] init]; // new in iOS 7.0
[self.textStorage addLayoutManager:layoutManager];
Во-первых, это сделать экземпляр из них, и создать Thier relationship.You должны добавить NSTextContainer
в UITextView
по initWithFrame:textContainer:
методом.
// UITextView
UITextView *newTextView = [[UITextView alloc] initWithFrame:textViewRect textContainer:container];
newTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
newTextView.scrollEnabled = YES;
newTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
// newTextView.editable = NO;
newTextView.font = [UIFont fontWithName:self.textStorage.fontName size:18.0];
newTextView.dataDetectorTypes = UIDataDetectorTypeAll;
self.textView = newTextView;
[self.view addSubview:self.textView];
Если хотите использовать UITextStorage
изменить атрибуты текста, вы можете использовать:
[_textStorage beginEditing]; // begin edit
[_textStorage endEditing]; // end edit
между ними вы можете редактировать текст, например:
[_textStorage beginEditing];
NSDictionary *attrsDic = @{NSTextEffectAttributeName: NSTextEffectLetterpressStyle};
UIKIT_EXTERN NSString *const NSTextEffectAttributeName NS_AVAILABLE_IOS(7_0); // NSString, default nil: no text effect
NSMutableAttributedString *mutableAttrString = [[NSMutableAttributedString alloc] initWithString:@"Letterpress" attributes:attrsDic];
NSAttributedString *appendAttrString = [[NSAttributedString alloc] initWithString:@" Append:Letterpress"];
[mutableAttrString appendAttributedString:appendAttrString];
[_textStorage setAttributedString:mutableAttrString];
[_textStorage endEditing];
Или изменение цвета:
[_textStorage beginEditing];
/* Dynamic Coloring Text */
self.textStorage.bookItem = [[BookItem alloc] initWithBookName:@"Dynamic Coloring.rtf"];
self.textStorage.tokens = @{@"Alice": @{NSForegroundColorAttributeName: [UIColor redColor]},
@"Rabbit": @{NSForegroundColorAttributeName: [UIColor greenColor]},
DefaultTokenName: @{NSForegroundColorAttributeName: [UIColor blackColor]}
};
[_textStorage setAttributedString:_textStorage.bookItem.content];
[_textStorage endEditing];
Вы нашли более подробную информацию по этому поводу? – dannyzlo
@DannyZlobinsky Не совсем. Здесь был ответ от пользователя с высокой репутацией, но он был удален (?!). Я все еще жду некоторых хороших ответов. – drasto
Вот хороший видеоурок, где показаны принципы NSTextStorage. Надеюсь, это поможет вам что-то, что есть, но выглядит интересно: https://www.youtube.com/watch?v=y7trOFDGVwA – juanmajmjr