有几次我想在创建类的实例之前使用XIB文件中的值;想到的两个是:
在这两种情况下,在实例化XIB实例之前,需要为HeightForCell计算单元格高度。
我考虑过的两种方法是:
由于需要将XIB属性复制为常量而烦恼,我没有(或没有)时间来实现这两种方法。
有没有其他人想出一个可行的解决方案,或者你只是与重复的常量一起生活?您认为上述哪种方法更好(更安全)?
感谢。
答案 0 :(得分:0)
我采用“垃圾实例”方法,缓存笔尖和高度:
-(NSNib *)nibWithName:(NSString *)nibName {
// Load the nib, or fetch it if we've already loaded it, then instantiate its contents
NSNib *nib = [_itemViewNibs objectForKey:nibName];
if (!nib) {
nib = [[NSNib alloc] initWithNibNamed:nibName bundle:nil];
[_itemViewNibs setObject:nib forKey:nibName];
}
return nib;
}
- (NSTableCellView *)firstTableCellInstantiatedFromNibWithName:(NSString *)nibName {
NSArray *nibObjects;
NSNib *nib = [self nibWithName:nibName];
if (![nib instantiateNibWithOwner:self topLevelObjects:&nibObjects]) return nil;
for (id obj in nibObjects)
if ([obj isKindOfClass:[NSTableCellView class]])
return (NSTableCellView *)obj;
return nil;
}
- (CGFloat)tableCellHeightForNibName:(NSString *)nibName {
NSNumber *height = [_itemViewHeights objectForKey:nibName];
if (! height) {
NSTableCellView *view = [self firstTableCellInstantiatedFromNibWithName:nibName];
height = [NSNumber numberWithFloat:view.frame.size.height];
[_itemViewHeights setObject:height forKey:nibName];
}
return height.floatValue;
}
...
CGFloat height = [self tableCellHeightForNibName:item.nibName];
...
view = [self firstTableCellInstantiatedFromNibWithName:item.nibName];