[英]Alternate backing store for NSTextStorage
每個示例均顯示NSMutableAttributedString作為“后備存儲”,用於保留文本和與查看/編輯文本相關的屬性。 如何使用替代項,例如std :: string或數據庫中的內容。 就像測試一樣,我創建了一個子類並對其進行硬編碼,以便在覆蓋所需方法時返回默認值。 但是,當我在iPhone 5設備上運行它時,它只會顯示黑屏,直到我按下“主頁”按鈕。 系統連續調用attributeAtIndex:location:effectiveRange:range:並且CPU使用率達到100%,並且該應用程序從不執行任何操作。 它確實調用過string:方法一次,但是隨后繼續調用attributeAtIndex:location:effectiveRange:range
這個例子:
@implementation MyTextStorage
{
}
- (id)init
{
self = [super init];
if (self)
{
}
return self;
}
#pragma mark - Reading Text
- (NSString *)string
{
return @"Static";
}
- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range
{
return @{NSFontAttributeName: [UIFont fontWithName:@"Noteworthy-Bold" size:36] } ;
}
#pragma mark - Text Editing
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str
{
// Empty - Don't allow editing
}
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range
{
// Empty - Don't allow editing
}
- (void)processEditing
{
[super processEditing];
}
@end
這是它的設置方式:
// property
self.textStorage = [MyTextStorage new];
// Create layout manager, and attach text storage to layout manager.
NSLayoutManager* layoutManager = [[NSLayoutManager alloc] init];
[self.textStorage addLayoutManager: layoutManager];
// Create text container and attach to layout manager
CGSize size = self.view.bounds.size;
size.height = size.height/2;
NSTextContainer* textContainer = [[NSTextContainer alloc] initWithSize: size];
[layoutManager addTextContainer: textContainer];
// Create text view, given text container.
CGRect frame1 = CGRectMake(0, 20, size.width, size.height);
UITextView *tv1 = [[UITextView alloc] initWithFrame:frame1 textContainer: textContainer];
[self.view addSubview: tv1];
我了解NSTextStorage是一個類集群,這似乎意味着它是一個抽象類工廠。 我真的不明白為什么我不能使用另一個“后備店”。 我的計划是使用std :: string(由於數據來自何處的原因),然后返回常量屬性樣式(如上述代碼)。 我一直在閱讀有關NSTextStorage,NSLayoutManager,NSTextContainer和NSTextView的所有資料,包括mac OS X文檔(即使我在iOS上也是如此)。 謝謝!
NSRangePointer
基本上是指向NSRange
的指針。 如果不為null,則需要在退出方法之前進行設置。 像這樣:
- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range {
if(range != NULL){
range->location = 0;
range->length = self.string.length;
}
return @{NSFontAttributeName: [UIFont fontWithName:@"Noteworthy-Bold" size:36] } ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.