RE:自动旋转,滚动,项目符号,带有属性字符串的缩进式UIScrollView [英] RE: autorotating, scrolling, bulleted, indented UIScrollView with attributed strings

查看:69
本文介绍了RE:自动旋转,滚动,项目符号,带有属性字符串的缩进式UIScrollView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一件令人费解的事情,并且由于我在SO贡献者的帮助下将它们组合在一起,因此发布结果似乎很公平(如下所示)。如果您要查找有关iOS和Core Text中的属性字符串并进行滚动的示例,请在此处进行汇编。

This was a doozy to produce, and since I had much help from SO contributors in putting it together, it seems fair to post the results (as an answer, below). If you’re looking for examples involving attributed strings in iOS and Core Text and scrolling, here they are assembled.

一些额外的要点:

包装:

这是通过属性字符串的lineBreakMode完成的,默认情况下为包装。您将无法从字符串中检索换行符(与Cocoa中的NSTextView在字符串中放置 \n个字符不同)。但是您不需要。您可以依靠Core Text的Framesetter在给定框架中为字符串提供高度,只要您已将引导信息放入属性字符串中即可。

This is done by the attributed string’s lineBreakMode, which defaults to wrapping. You won’t be able to retrieve the soft line breaks from the string (unlike in Cocoa, where NSTextView puts ‘\n’ chars in the strings). But you don’t need to. You can rely on Core Text’s Framesetter to provide you with the string’s height in a given frame — as long as you have put leading info into the attributed string.

CATextLayer:

使用起来很方便。您所要做的就是分配一个属性字符串,然后包装并绘制。如果您要用选择的字体显示短字符串,那太好了。但是CATextLayer无法识别前导或缩进,因此对于该项目,我直接吸引到了CALayer。

It’s handy to work with. All you have to do is assign an attributed string and it wraps and draws. If you have a short string to display with a chosen font, it’s great. But CATextLayer doesn’t recognize leading or indentation, so for this project I drew directly to CALayer.

字体:

我大部分时间都坚持使用CTFontRef,因为它是在iOS中构建属性字符串所必需的,并且可以提供精确的前导,但是有时候使用UIFont更为容易。这是一种将CTFontRef( fontr )转换为UIFont的方法:

I stuck with CTFontRef for the most part, since it is required for building an attributed string in iOS and it gives accurate leading, but there are times when it’s easier to work with a UIFont. Here’s a way to convert a CTFontRef (fontr) to a UIFont:

NSString *sFontName = (NSString *)CTFontCopyName(fontr, kCTFontPostScriptNameKey);
UIFont *font = [UIFont fontWithName:sFontName size:CTFontGetSize(fontr)];
CGSize sizeString = [string sizeWithFont:font];
[sFontName release];

如果您是从头开始创建UIFont的,请注意它会在字体名称,也可以将它们粉碎在一起,但粗体必须用连字符分隔:

If you create a UIFont from scratch, be aware that it will accept spaces in the family part of the font name, or you can smash them together, but "Bold" must be separated by a hyphen:

self.fontTickerNormal = [UIFont fontWithName:@"Helvetica Neue" 
                                        size:18.0f]; // OK
self.fontTickerIndent = [UIFont fontWithName:@"HelveticaNeue" 
                                        size:16.0f]; // OK too 
self.fontTickerBold = [UIFont fontWithName:@"HelveticaNeue-Bold" 
                                      size:18.0f];   // both the smash and the hyphen are required

CTFontRef更简单。所有名称部分都可以用空格分隔。以下工作正常:

CTFontRef is more straightforward. All the name parts can be separated by spaces. The following works fine:

 self.fontrTickerBold = CTFontCreateWithName((CFStringRef)@"Helvetica Neue Bold", 18.0f, NULL);

下面的示例...

推荐答案

准备组件:
大多数示例都更易于阅读,因为它们将字符串及其属性都集中在一个地方(即清晰的示例),但是如果您不了解所有组件,则会得到访问错误的异常当视图使用字符串时,最好在UIViewController的viewDidLoad中设置所有内容:

Prepare the Components: Most examples are easier to read because they assemble the strings and their attributes all in one place (i.e. clear example), but if you don’t hang onto all the components, you’ll get bad-access exceptions when the views use the strings, so it seems best to set everything up in the UIViewController’s viewDidLoad:

- (void)viewDidLoad {
[super viewDidLoad];

// FONTS ETC.

// Prepare fonts for the ticker display.
self.fontrTickerNormal = CTFontCreateWithName((CFStringRef)@"Helvetica Neue", 18.0f, NULL);
self.fontrTickerBold = CTFontCreateWithName((CFStringRef)@"Helvetica Neue Bold", 18.0f, NULL);
self.fontrTickerIndent = CTFontCreateWithName((CFStringRef)@"Helvetica Neue", 16.0f, NULL);
// Determine width of bullet sub-indent
// (Use a UIFont and UIKit's sizeWithFont. No need to fuss with framesetter and leading here; all we need is width.)
UIFont *fontTickerIndent_uif = [UIFont fontWithName:@"Helvetica Neue" size:16.0f]; 
NSString *stringWithBullet = [NSString stringWithUTF8String:"\u2022"]; // bullet char
NSString *stringWithBulletPlusSpace = [stringWithBullet stringByAppendingString:@"  "];
CGSize sizeBulletPlusSpace = [stringWithBulletPlusSpace sizeWithFont:fontTickerIndent_uif];
self.fWidthBulletPlusSpace = sizeBulletPlusSpace.width;
// Prepare bulleted string to which text can be appended
NSString *stringBulletBuild = [@"\n" stringByAppendingString:stringWithBullet];
stringBulletBuild = [stringBulletBuild stringByAppendingString:@"\t"];
self.sBulletedLineBreak = stringBulletBuild;

// Initialize the collections that will hold onto the individual strings and dicts via alloc, as opposed to an autoreleased method, so that we can control the order in which they are released in viewDidUnload. (If dicts were to be released before the strings that use them, there would be a bad-access crash):
NSMutableArray *asmarrTickerStringsNew = [[NSMutableArray alloc] initWithCapacity:20]; // guess
self.asmarrTickerStrings = asmarrTickerStringsNew;
[asmarrTickerStringsNew release];
NSMutableArray *dmarrTickerAttributesNew = [[NSMutableArray alloc] initWithCapacity:20]; // one per string
self.dmarrTickerAttributes = dmarrTickerAttributesNew;
[dmarrTickerAttributesNew release];
// Don't initialize the cumulative-string ppty (mattrStgr) here. There is no way of appending to an empty CFMutableAttributedStringRef, so you have to wait till the first string goes through addProgressTickerLine.

// STYLE SETTINGS:

// paragStyleNormal:
CFIndex countSettings = 3; // normal and bold styles both have 3 settings
// - left alignment (the default, but just in case)
CTTextAlignment alignment = kCTLeftTextAlignment;
CTParagraphStyleSetting styleAlignLeft = { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &alignment };
// - wrapping (again the default, but just in case)
CTLineBreakMode wrapping = kCTLineBreakByWordWrapping;
CTParagraphStyleSetting styleWrapped = { kCTParagraphStyleSpecifierLineBreakMode, sizeof(CTLineBreakMode), &wrapping };
// - normal leading (so framesetter calculates the correct height)
CGFloat fLeadingNormal = CTFontGetLeading(self.fontrTickerNormal);
CTParagraphStyleSetting styleLeadingNormal = { kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof(CGFloat), &fLeadingNormal };
CTParagraphStyleSetting arrSettingsNormal[] = { styleAlignLeft, styleWrapped, styleLeadingNormal };
self.paragStyleNormal = CTParagraphStyleCreate(arrSettingsNormal, countSettings);
// paragStyleBold:
// - bold leading (otherwise this style is same as normal)
CGFloat fLeadingBold = CTFontGetLeading(self.fontrTickerBold);
CTParagraphStyleSetting styleLeadingBold = { kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof(CGFloat), &fLeadingBold };
CTParagraphStyleSetting arrSettingsBold[] = { styleAlignLeft, styleWrapped, styleLeadingBold };
self.paragStyleBold = CTParagraphStyleCreate(arrSettingsBold, countSettings);
// paragStyleIndent:
// - indented leading (font is smaller)
CGFloat fLeadingIndent = CTFontGetLeading(self.fontrTickerIndent);
CTParagraphStyleSetting styleLeadingIndent = { kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof(CGFloat), &fLeadingIndent };
// - Indent the first line up to the bullet.
CGFloat indentFirstLineHead = 15.0f; 
CTParagraphStyleSetting styleFirstLineHeadIndent = { kCTParagraphStyleSpecifierFirstLineHeadIndent, sizeof(CGFloat), &indentFirstLineHead };
// - Add a tab stop to allow for the bullet and some following space.  
self.tabStop = CTTextTabCreate(alignment, (double)self.fWidthBulletPlusSpace, NULL); 
CTTextTabRef tabStopPtr[] = { self.tabStop };
self.cfarrTabStop = CFArrayCreate(NULL, (const void **) tabStopPtr, 1, NULL); 
CTParagraphStyleSetting styleTabStops = { kCTParagraphStyleSpecifierTabStops, sizeof(CTTextTabRef), &cfarrTabStop };
// - Indent the wrapped lines to the same point as the tab stop.
CGFloat indentHead = indentFirstLineHead + self.fWidthBulletPlusSpace;
CTParagraphStyleSetting styleHeadIndent = { kCTParagraphStyleSpecifierHeadIndent, sizeof(CGFloat), &indentHead };
// Put paragStyleIndent together.
countSettings += 3; // 3 style settings added (firstLineHeadIndent, tabStop, and HeadIndent)
CTParagraphStyleSetting arrSettingsIndent[] = { styleAlignLeft, styleWrapped, styleLeadingIndent, styleFirstLineHeadIndent, styleTabStops, styleHeadIndent };  
self.paragStyleIndent = CTParagraphStyleCreate(arrSettingsIndent, countSettings);

// LAYER AND SCROLLVIEW

// Set up the layer for the progress ticker.
CGSize sizeTicker = self.svProgressTicker.layer.bounds.size;
// Frame the layer:
/*
 - Don't add any padding to the X origin; the scrollview apparently figures some into its bounds automatically.
 - Do add some padding to the Y origin; otherwise the first string will hug the top.
 - Decrease the width to allow for the scrollbar, which the scrollview bounds do not account for.
 - Height is 0 for now, since it doesn't have any strings yet.
 */
CGRect rectTickerInset = CGRectMake(0.0f, kMargin, sizeTicker.width - kMargin, 0.0f);
CALayer *layerTicker = [CALayer layer];
[layerTicker setFrame:rectTickerInset];
// Assign this controller as the delegate and add it to the scrollview's root layer. 
// (See headnote to the drawLayer method.)
[layerTicker setDelegate:self];
self.layProgressTicker = layerTicker;
[svProgressTicker.layer addSublayer:self.layProgressTicker];
// Set the scrollView's contentSize per the layer's frame -- which will become taller with each appended string until it exceeds the scrollView's bounds.
[self.svProgressTicker setContentSize:CGSizeMake(rectTickerInset.size.width, rectTickerInset.size.height)];
[self.svProgressTicker setClipsToBounds:YES]; // otherwise the contents will overflow the border.

}

追加字符串:

(使用这些常量:)

#define kTickerStyleNormal           0
#define kTickerStyleIndent           1
#define kTickerStyleBold             2
#define kTickerStyleFirstLine        3

/**
 Appends the string arg to the Progress Ticker scrollView, styled per uiStyle.
 Note: String arg should NOT have any line breaks.
 */
- (void) addProgressTickerLine:(NSString *)string 
                       inStyle:(uint8_t)uiStyle {

// Determine the font.
CTFontRef fontr = nil;
switch (uiStyle) {
    case kTickerStyleNormal:
        fontr = self.fontrTickerNormal;
        break;
    case kTickerStyleIndent:
        fontr = self.fontrTickerIndent;
        break;
    case kTickerStyleBold:
        fontr = self.fontrTickerBold;
        break;
    case kTickerStyleFirstLine:
        fontr = self.fontrTickerBold;
        break;
    default:
        fontr = self.fontrTickerNormal;
        break;
}

// Prepare the paragraph style (preassembled in viewWillAppear), to govern inter-line height and indentation. 
// At the same time, add the initial line break.
CTParagraphStyleRef paragStyle = NULL; 
switch (uiStyle) {
    case kTickerStyleNormal:
        string = [@"\n" stringByAppendingString:string];
        paragStyle = self.paragStyleNormal;
        break;
    case kTickerStyleBold:
        // For main un-indented lines, simply add a line break.
        string = [@"\n" stringByAppendingString:string];
        paragStyle = self.paragStyleBold;
        break;
    case kTickerStyleFirstLine: {
        paragStyle = self.paragStyleBold;
        // No line break for the first line.
        // (Q: Why not avoid this case by putting line break at the end, rather than the beginning?)
        // (A: The indented string would then require 2 steps to sandwich it between the bullet-tab and the line break.)
        break;
    }
    case kTickerStyleIndent: {
        // For indented bullet lines, prepend lineBreak-bullet-tab to the string.
        string = [self.sBulletedLineBreak stringByAppendingString:string];
        // Assign the indented paragStyle.
        paragStyle = self.paragStyleIndent; 
        break;
    }
    default: // just in case
        paragStyle = self.paragStyleNormal;
        break;
}

// Determine the text (foreground) color per...
UIColor *colorHSV = [UIColor blueColor]; // switch-case omitted

// PUT IT ALL TOGETHER.

// Combine the above into a dictionary of attributes.
CFStringRef keys[] = { kCTFontAttributeName, kCTParagraphStyleAttributeName, kCTForegroundColorAttributeName };
CFTypeRef values[] = { fontr, paragStyleIndent, colorHSV.CGColor };
CFDictionaryRef dictr = CFDictionaryCreate(NULL, 
                                           (const void **)&keys, 
                                           (const void **)&values,
                                           sizeof(keys) / sizeof(keys[0]), 
                                           &kCFTypeDictionaryKeyCallBacks, 
                                           &kCFTypeDictionaryValueCallBacks);
[self.dmarrTickerAttributes addObject:(id)dictr]; // provides for release

// Use the attributes dictionary to make an attributed string out of the plain string.
CFAttributedStringRef attrStgr = CFAttributedStringCreate(kCFAllocatorDefault, (CFStringRef)string, dictr);    
[self.asmarrTickerStrings addObject:(id)attrStgr]; // provides for release
// Adding an object to a collection increments its retain count, so attrStgr are now at count 2 and should be decremented to 1; they will be brought to 0 upon release of the collections.
CFRelease(attrStgr);
CFRelease(dictr);

// If cumulative attrStg is nil, initialize it with a maxLength of 0 to indicate that it is unlimited.
if (!self.mattrStgr)
    self.mattrStgr = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 0, attrStgr); 
// Else append the newly completed attrStg, using the method suggested in the CFMutableAttributedString class ref overview.
else {
    CFRange rangeAppend = CFRangeMake(CFAttributedStringGetLength(self.mattrStgr), 0);
    CFAttributedStringReplaceAttributedString(self.mattrStgr, rangeAppend, attrStgr);
}

// DISPLAY IT. 

// Now that the new string has been appended, call the method that will adjust the contentSize, trigger the draw method, and scroll to the end.
[self adjustProgressTickerFrame];

// Do NOT release attrstg or any of its styling components here. They are needed cumulative string property is voided. They have been propertized so that they can be released in dealloc (here in viewDidUnload).

}

调整高度,调用drawLayer,然后滚动到底部:

Adjust the height, call drawLayer, and scroll to bottom:

/**
 Adjust the height of the scrollView and its content layer to accommodate newly appended strings and/or orientation change, redraw the layer, and scroll to the bottom.
 Called at the end of addProgressTickerLine and upon willAnimateRotationToInterfaceOrientation.
 */
- (void) adjustProgressTickerFrame {

// Get the width within which the text has to fit in the view's current frame.
CGSize sizeTickerView = self.svProgressTicker.layer.bounds.size;
CGFloat fWidthInset = sizeTickerView.width - kMargin;

// Make a framesetter in order to get the size of the cumulative string.
/*
 Note re Leading: 
 - The framesetter will suggest too short a height unless the attributed string has paragraphStyle attributes that specify the leading.
 - But if you attempt to do an efficient setNeedsDisplay:InRect routine, drawing only the last-appended string per its individual height, framesetter will report the the hard line breaks as a full line, not just as leading, so you'll end up with dimensions that are much too tall. There's no choice but to get the full size and draw the full cumulative string each time.
 */
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(self.mattrStgr);
CFIndex length = CFAttributedStringGetLength(self.mattrStgr);
CFRange textRange = CFRangeMake(0, length);
CFRange fitRange;
CGSize sizeString = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, textRange, NULL, CGSizeMake(fWidthInset, CGFLOAT_MAX), &fitRange);

// Round the reported height up. Dimensions are reported as very precise fractions, but framing and drawing is by whole pixels.
CGFloat fHeight = ceilf(sizeString.height);

// Reframe the layer.
CGRect rectTickerInset = CGRectMake(0.0f, kMargin, sizeTickerView.width - kMargin, fHeight); 
[self.layProgressTicker setFrame:rectTickerInset];

// Adjust the scrollView's contentSize.
// (It should be slightly taller than the layer, to add padding at top and bottom.)
[self.svProgressTicker setContentSize:CGSizeMake(fWidthInset, (fHeight + (kMargin*2)))];

// Redraw the entire layer.
[self.layProgressTicker setNeedsDisplay];

// If the layer is now taller than the scrollView's bounds, scroll down.
// Do NOT use animation. 
// (If you do when the view first appears, it won't scroll down far enough, should the view be assigned lots of string content initially. (Presumably the initial autorotation anim prevents this one from being completed.) And afterwards, it doesn't make any difference; there's a spring action that happens regardless.)
CGFloat fHeightExcess = fHeight - (sizeTickerView.height - (kMargin*2)); 
if (fHeightExcess > 1.0f)
    [self.svProgressTicker setContentOffset:CGPointMake(0.0f, fHeightExcess) animated:NO];

}

绘制:

/**
 CALayer's delegate method for drawing its content, triggered by calling setNeedsDisplay on the layer. 

 This controller is assigned as the layer's delegate, and calls setNeedsDisplay when:
 1) a string is appended
 2) the device is rotated into a different aspect ratio

 Q: Why not subclass UIScrollView and have IT be the delegate? After all, the class ref says the view associated with the layer must be the delegate.
 A1: Apparently "associated" in Apple-speak means as in view to its ROOT layer. Sublayers can have any delegate you choose.
 A2: If scrollView is the delegate and does the content drawing, the app will crash. ScrollView probably issues setNeedsDisplay:inRect: gazillions of times as it scrolls, overwhelming the processor.
 */
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {

// Get the rect of the entire area available for drawing.
// (We cannot use the layer's frame rect directly because it has origin insets; they would be doubled if used here too.)
CGRect drawingRect = CGRectMake(0.0f, 0.0f, self.layProgressTicker.frame.size.width, self.layProgressTicker.frame.size.height); 

// Turn the context upside down to match the layer's orientation.
// (The context origin is at the lower left, whereas the layer origin is at the upper left.)
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
CGContextTranslateCTM( ctx, drawingRect.origin.x, drawingRect.size.height );
CGContextScaleCTM( ctx, 1, -1 );

// Make a rectangular path in which to draw.
CGMutablePathRef path = CGPathCreateMutable(); 
CGPathAddRect(path, NULL, drawingRect);

// Use Core Text's framesetter to frame the cumulative (mutable) attributed string inside the rectangular path.
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(self.mattrStgr);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);    
CFRelease(framesetter); // ok to release here; it's not part of "frame"
CFRelease(path);

// Draw the framesetter frame.
CTFrameDraw(frame, ctx);
CFRelease(frame);

}

自动旋转:

/*
 Autorotation methods are called in this order:
    1) shouldAutorotate
    2) willRotate
    3) willAnimate
    4) didRotate
 */
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {  
// Return YES to support all 4 orientations.
return YES;
}

- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
// "When this method is called, the interfaceOrientation property still contains the view’s original orientation." (So hang onto it.)
// You can't wait until willAnimate because, by then, that property will have been set to the new orientation.
// Which leaves a mystery: The didRotateFromInterfaceOrientation is called AFTER willAnimate, and at that point the view controller still is able to send in the fromInterfaceOrientation arg.
self.bFromPortrait = UIInterfaceOrientationIsPortrait([self interfaceOrientation]);    
}

- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {

// If rotating from portrait to landscape or vice versa, the text layers need adjustment. 
BOOL bToPortrait = UIInterfaceOrientationIsPortrait(toInterfaceOrientation);

if (self.bFromPortrait != bToPortrait) 
    [self adjustProgressTickerFrame];

}

我想我说对了:这是卸载所有这些东西(保留的属性也会在dealloc中释放):

I think I’ve got this right: Here’s how to unload all this stuff (the retained properties are also released in dealloc):

- (void)viewDidUnload {

// It's unlikely that this view will go away and then come back, so viewDidLoad assumes all properties are null -- therefore nullify/release EVERYTHING here.

self.svProgressTicker = nil;
self.layProgressTicker = nil;
self.vSyncInstructions = nil;
self.tlSyncInstructions = nil;
self.btnSyncEtc = nil;

// Release the cumulative attributed string BEFORE releasing any of its component strings.
CFRelease(self.mattrStgr);
// Nullifying the retained collections will release them -- and their contents, whose retainCounts were incremented upon addition to the collection. So it's important to nullify the strings collection first, then the attr dicts.
self.asmarrTickerStrings = nil;
self.dmarrTickerAttributes = nil;
// Now we can release the "created" settings, then their components.
CFRelease(self.paragStyleNormal);
CFRelease(self.paragStyleBold);
CFRelease(self.paragStyleIndent);
CFRelease(self.tabStop);
CFRelease(self.cfarrTabStop);
CFRelease(self.fontrTickerNormal);
CFRelease(self.fontrTickerBold);
CFRelease(self.fontrTickerIndent);
CFRelease(self.fontrInstructions);
self.fontInstructionsBenchmark = nil;

[super viewDidUnload];

}


这篇关于RE:自动旋转,滚动,项目符号,带有属性字符串的缩进式UIScrollView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆