【发布时间】:2011-03-01 00:05:54
【问题描述】:
我有一个带有 NSBox 子视图的视图(为阴影启用了 CA),我试图在 awakeFromNib 期间将我的 NSView 子类动态添加到该框中。
根据用户的不同,这些 NSView 的数量会有所不同,因此我编写了一些代码来确定要在框中很好地排列它们的行数和列数。 (我已经考虑过 NSMatrix,但它并没有按照我的意图进行布局)
问题是awakeFromNib方法结束后,子视图突然消失了! 我已经放了很多 NSLog 语句来尝试追踪它,我发现的只是子视图在它们消失之前显然已添加到 NSBox 中。运行应用程序时,子视图会短暂出现,然后在动画完成后消失。
这是我的 awakeFromNib 方法:
-(void)awakeFromNib
{
//Fill an array with buttons for each company object
buttons = [[NSMutableArray alloc] init];
for (BCCompany *c in [[[BCParser sharedParser] managedObjectContext] fetchObjectsForEntityName:@"BCCompany" withPredicate:nil andSortDescriptor:nil])
{
CompanyButton *button = [[CompanyButton alloc] initWithFrame:NSMakeRect(0, 0, 150, 150)];
[button setCompanyName:[c name]];
[buttons addObject:button];
}
//Determine how many columns we can fit across the window -- 100px padding on each side -- 150px width for each button
int noOfColumns = ([[self view] frame].size.width - 200) / 150;
if ([buttons count] < noOfColumns)
noOfColumns = [buttons count];
//Determine how many rows will be needed
int noOfRows = ([buttons count] + noOfColumns - 1) / noOfColumns;
//Resize and reposition the box
[whiteBox setFrameSize:NSMakeSize((noOfColumns * 150) + 60, (noOfRows * 150) + 20)];
[whiteBox setFrameOrigin:NSMakePoint(NSMidX([[self view] frame]) - ([whiteBox frame].size.width/2), NSMidY([[self view] frame]) - ([whiteBox frame].size.height/2) - 100)];
//Now iterate through each row and add items, checking if it's the last row
subviewsToAdd = [[NSMutableArray alloc] init];
for (int i=0; i<noOfRows; i++)
{
NSRect boxRect = [whiteBox frame];
NSArray *tempArray = [[NSArray alloc] init];
if (i == (noOfRows-1)) {
//Final row
tempArray = [buttons subarrayWithRange:NSMakeRange(i*noOfColumns, [buttons count])];
for (int j=0; j<[tempArray count]; j++)
{
//Iterate through the remaining buttons and add them
NSPoint buttonOrigin = NSMakePoint(5 + (j * 150), (boxRect.size.height) - (150 * (i+1)));
NSRect buttonRect = NSMakeRect(buttonOrigin.x, buttonOrigin.y, 150, 150);
[[tempArray objectAtIndex:j] setFrame:buttonRect];
NSLog(@"%@ Frame -- X:%f Y:%f -- j:%i", [[tempArray objectAtIndex:j] companyName], [[tempArray objectAtIndex:j] frame].origin.x, [[tempArray objectAtIndex:j] frame].origin.y, j);
[subviewsToAdd addObject:[tempArray objectAtIndex:j]];
}
} else {
//Not the final row
tempArray = [buttons subarrayWithRange:NSMakeRange(i*noOfColumns, noOfColumns)];
for (int j=0; j<noOfColumns; j++)
{
//Position each one on this row
NSPoint buttonOrigin = NSMakePoint(5 + (j * 150), (boxRect.size.height) - (150 * (i+1)) - 10);
NSRect buttonRect = NSMakeRect(buttonOrigin.x, buttonOrigin.y, 150, 150);
[[tempArray objectAtIndex:j] setFrame:buttonRect];
[subviewsToAdd addObject:[tempArray objectAtIndex:j]];
}
}
}
[whiteBox setSubviews:subviewsToAdd];
[whiteBox setNeedsDisplay:YES];
}
对此的任何帮助将不胜感激!
史蒂夫
【问题讨论】:
-
顺便说一句:如果有任何不同,垃圾收集就会开启
标签: objective-c cocoa nsview appkit nsviewcontroller