编辑:下面详细问题的简化版本:您可以通过子类 drawRect 更新 UIView 的边界而不导致视图内容拉伸吗?
我正在构建一个新闻阅读器应用程序,并且一直在研究如何将 UIView 拆分为列并仍然对内容进行分页。我相信我已经对列进行了基本编码(将 XML 节点内容按段落拆分为数组,然后通过检测不切断段落所需的总面积进行解析。)
我遇到的问题是我无法在没有文本拉伸的情况下更新 ContentBounds,即使里面的内容足够大以支持未拉伸的视图。
基本上是这样的:
contentBounds = CGSizeMake(self.bounds.size.width, self.bounds.size.height+COLUMN_YPOS);
[renderer updateContentBounds:contentBounds];
导致这个:(下图的完整代码)
- (void)drawRect:(CGRect)rect
{
NSString *string = contentString;
[string stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n\n"];
// column width
int COLUMN_WIDTH = self.bounds.size.width/2-40;
int COLUMN_HEIGHT = self.bounds.size.height-100;
int COLUMN_XPOS = 20;
int COLUMN_YPOS = 0;
int PAGE_HEIGHT = COLUMN_HEIGHT + 40;
CGSize maximumSize = CGSizeMake(COLUMN_WIDTH, COLUMN_HEIGHT-20);
NSArray *paragraphs = [string componentsSeparatedByString:@"\n"];
NSString *textBuffer = @"";
NSString *preBuffer = @"";
NSString *currentStringSegment;
for (int i=0; i<[paragraphs count]; i++) {
currentStringSegment = [paragraphs objectAtIndex:i];
preBuffer = textBuffer;
textBuffer = [textBuffer stringByAppendingString:@"\n\n"];
textBuffer = [textBuffer stringByAppendingString:currentStringSegment];
CGSize expectedSize = [textBuffer sizeWithFont:[UIFont fontWithName:@"Times New Roman" size:16] constrainedToSize:CGSizeMake(COLUMN_WIDTH, COLUMN_HEIGHT) lineBreakMode:NSLineBreakByWordWrapping];
if(expectedSize.height > maximumSize.height){
[preBuffer drawInRect:CGRectMake(COLUMN_XPOS, COLUMN_YPOS, COLUMN_WIDTH, COLUMN_HEIGHT) withFont:[UIFont fontWithName:@"Times New Roman" size:16] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];
i--;
textBuffer = @"";
preBuffer = @"";
if(COLUMN_XPOS > 20) {
COLUMN_XPOS = 20;
COLUMN_YPOS += PAGE_HEIGHT;
} else {
COLUMN_XPOS = COLUMN_WIDTH + 60;
}
}
}
if(![preBuffer isEqualToString:@""] && preBuffer != nil){
[preBuffer drawInRect:CGRectMake(COLUMN_XPOS, COLUMN_YPOS, COLUMN_WIDTH, COLUMN_HEIGHT) withFont:[UIFont fontWithName:@"Times New Roman" size:16] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];
}
contentBounds = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
[renderer updateContentBounds:contentBounds];
}