问题描述
我有一个NSPopUpButtonCell
的自定义子类,以便可以覆盖它的drawBezelWithFrame:inView:
方法.
I have a custom subclass of NSPopUpButtonCell
so that I can overwrite its drawBezelWithFrame:inView:
method.
当前,我必须使用initTextCell:pullsDown:
创建一个新实例,然后手动复制其所有属性.这相当乏味且容易出错,因为我可能会缺少一些属性.
Currently, I have to create a fresh instance using initTextCell:pullsDown:
and then copy all its properties by hand. That's rather tedious and error-prone as I may be missing some properties.
我想知道我是否可以代替initWithCoder:
来完成此任务.我想我应该能够将现有NSPopUpButtonCell
实例中的数据归档到NSCoder
对象中,例如到NSKeyedArchiver
中,然后将该数据归档回我的NSPopUpButtonCell
子类中.但是我不知道该怎么做.
I wonder if I can use initWithCoder:
for this task instead. I imagine I should be able to file the data from the existing NSPopUpButtonCell
instance into an NSCoder
object, e.g. into NSKeyedArchiver
, and then file that data back into my NSPopUpButtonCell
subclass. But I can't figure out how to accomplish that.
推荐答案
好像我以前使用了错误的函数.隔离非常简单.
Looks like I just used the wrong functions before. The solition is pretty straight-forward.
此代码将NSPopUpButtonCell的属性复制到其子类中,以便我可以覆盖其draw ...方法:
This code duplicates the properties of a NSPopUpButtonCell into a subclass of it, so that I can overwrite its draw... methods:
@interface MyPopup : NSPopUpButton
@end
@implementation MyPopup
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
// Set up the archiver
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// Archive the cell's properties
[self.cell encodeWithCoder:arch];
[arch finishEncoding];
// Set up the unarchiver
NSKeyedUnarchiver *ua = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// Create a subclass of the cell's class, using the same properties
MyCell *newCell = [[MyCell alloc] initWithCoder:ua];
// Assign the new subclass object as the NSButton's cell.
self.cell = newCell;
}
return self;
}
以下显示了使用自定义NSButtonCell子类的另一种更简洁的方法:对文本使用NSPopupButton的全宽度,没有箭头
Another, cleaner, way to use a custom NSButtonCell subclass is shown here: Using full width of NSPopupButton for text, no arrows
这篇关于如何将符合NSCoding的对象克隆到其子类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!