Могу ли я использовать NSAttributedString в основном тексте в iOS?

Я пытаюсь понять, как взять NSAttributedString и использовать его в основном тексте на iPad. Я посмотрел одно из видео WWDC (110), в котором есть слайды (но нет исходного кода), и в нем описывается, как создать NSAttributedString, а затем просто поместить его в CTFramesetterRef:

CTFontRef helveticaBold = CTFontCreateWithName( CFSTR("Helvetica-Bold"), 24.0, NULL);

NSString* unicodeString = NSLocalizedString(@"TitleString", @"Window Title");
CGColorRef color = [UIColor blueColor].CGColor; NSNumber* underline = [NSNumber numberWithInt:kCTUnderlineStyleSingle|kCTUnderlinePatternDot];
NSDictionary* attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:helveticaBold, (NSString*)kCTFontAttributeName, color, (NSString*)kCTForegroundColorAttributeName, underline, (NSString*)kCTUnderlineStyleAttributeName, nil];
NSAttributedString* stringToDraw = [[NSAttributedString alloc] initWithString:unicodeString attributes:attributesDict];

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(stringToDraw);

CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CFRelease(framesetter);
CTFrameDraw(frame, context);
CFRelease(frame);

Но когда я пытаюсь это сделать, он выдает ошибку:

Передача аргумента 1 'CTFramesetterCreateWithAttributedString' из несовместимого типа указателя

Являются ли CFAttributedString и NSAttributedString «бесплатными мостами»? Я где-то читал, что это верно только для OSX, но именно так Apple делает это в своей демонстрации...

Спасибо!

:-Джо


person jowie    schedule 22.09.2010    source источник
comment
Вам удалось сделать так, чтобы пунктирное подчеркивание отображалось? Я получаю только одно простое подчеркивание под текстом.   -  person learner2010    schedule 19.11.2012


Ответы (3)


Исходный код WWDC10 можно загрузить здесь. Кроме того, используйте бесплатный мост и явно преобразуйте stringToDraw в CFAttributedStringRef.

person jer    schedule 22.09.2010
comment
Спасибо, но ссылка, которую вы дали, продолжает говорить, что срок действия моего сеанса истек (даже когда я снова пытаюсь войти в систему). Я скачал пример кода WWDC10 раньше, но 110 не было в нем :( - person jowie; 22.09.2010
comment
Просто измените NSAttributedString* stringToDraw = [[NSAttributedString alloc] initWithString:unicodeString attributes:attributesDict]; на CFAttributedStringRef stringToDraw = (CFAttributedStringRef)[[NSAttributedString alloc] initWithString:unicodeString attributes:attributesDict]; - person jowie; 20.09.2012

Ты почти там. Просто приведите CTFontRef к типу id при добавлении его в словарь атрибутов.

CTFontRef helveticaBold = CTFontCreateWithName( CFSTR("Helvetica-Bold"), 24.0, NULL);

NSString* unicodeString = NSLocalizedString(@"TitleString", @"Window Title");

CGColorRef color = [UIColor blueColor].CGColor; 
NSNumber* underline = [NSNumber numberWithInt:
    kCTUnderlineStyleSingle|kCTUnderlinePatternDot];

NSDictionary* attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
                    (id)helveticaBold, (NSString*)kCTFontAttributeName, 
                    color, (NSString*)kCTForegroundColorAttributeName, 
                    underline, (NSString*)kCTUnderlineStyleAttributeName, nil];

NSAttributedString* stringToDraw = [[NSAttributedString alloc] 
                            initWithString:unicodeString
                            attributes:attributesDict];
person nevan king    schedule 24.04.2012

код WWDC Session 110 CTPageViewer теперь является частью официального примера кода Apple:

http://developer.apple.com/library/ios/#samplecode/CoreTextPageViewer/Listings/ReadMe_txt.html

person Flori    schedule 19.09.2012