If a subclass is defined as MyView
that subclasses UIView
, and in the Interface Builder, the view is clicked on, and the Custom Class is already set to MyView
.
如果子类被定义为子类UIView的MyView,并且在Interface Builder中,则单击视图,并且自定义类已设置为MyView。
But in ViewController's viewDidLoad
,
但是在ViewController的viewDidLoad中,
self.view.foo = ... ;
will create a compile error that says foo
is not a property of UIView
. I then print out the class of self.view
:
将创建一个编译错误,说foo不是UIView的属性。然后我打印出self.view类:
NSLog(@"Class of view is %@", NSStringFromClass([self.view class]));
and sure enough, it prints out MyView
. Also, not only the first line will not compile, Xcode will not "auto complete" the word "foo" as well. But clearly, the class prints out no as UIView
but is MyView
, and in my class definition of MyView
, I did say:
果然,它打印出MyView。此外,不仅第一行不会编译,Xcode也不会“自动完成”单词“foo”。但显然,该类打印出的不是UIView,而是MyView,在我的MyView类定义中,我说过:
@property (nonatomic, strong) NSMutableArray *foo;
in the interface .h
file, and also in the implementation .m
file:
在接口.h文件中,以及实现.m文件中:
@synthesize foo;
and MyView.h
is imported in ViewController.h
as well. Why is this so and how to fix this?
MyView.h也在ViewController.h中导入。为什么会如此以及如何解决这个问题?
1 个解决方案
#1
3
Your UIViewController doesn't know that its view is meant to be an instance of your MyView
subclass.
你的UIViewController不知道它的视图是你的MyView子类的一个实例。
You'll need to cast it
你需要施展它
MyView *myView = (MyView *)self.view;
myView.foo = @"Whatever";
If you want to simplify this, you can also subclass UIViewController and then just always reference self.myView
in your MyViewController subclasses instead of self.view
:
如果你想简化这个,你也可以继承UIViewController,然后总是在你的MyViewController子类中引用self.myView而不是self.view:
@interface MyViewController : UIViewController
@property (nonatomic, strong) MyView *myView;
@end
@implementation MyViewController
@synthesize myView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.myView = (MyView *)self.view;
}
return self;
}
@end
#1
3
Your UIViewController doesn't know that its view is meant to be an instance of your MyView
subclass.
你的UIViewController不知道它的视图是你的MyView子类的一个实例。
You'll need to cast it
你需要施展它
MyView *myView = (MyView *)self.view;
myView.foo = @"Whatever";
If you want to simplify this, you can also subclass UIViewController and then just always reference self.myView
in your MyViewController subclasses instead of self.view
:
如果你想简化这个,你也可以继承UIViewController,然后总是在你的MyViewController子类中引用self.myView而不是self.view:
@interface MyViewController : UIViewController
@property (nonatomic, strong) MyView *myView;
@end
@implementation MyViewController
@synthesize myView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.myView = (MyView *)self.view;
}
return self;
}
@end