我有一个带有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];
}
非常感谢任何有关这方面的帮助!
史蒂夫
答案 0 :(得分:0)
在NSView的-setSubviews:
此方法标记受影响的视图 和窗口区域需要显示。
如果您未在-setNeedsDisplay
上再次致电whiteBox
会怎样?