我想创建一个 ViewController 类的实例:
ViewController *viewConnection = [[ViewController alloc]init];
self.image.center = CGPointMake(self.image.center.x + 1, self.image.center.y);
if (CGRectIntersectsRect(self.image.frame, viewConnection.otherImage.frame)) {
[self.movementTimer invalidate];
}`
当类中的图像命中 ViewController 中的图像时,它不会进入 if 语句,有人可以告诉我为什么吗?
最佳答案
要访问变量和 socket ,您必须在 .h 文件中定义属性:
@interface ViewController : UIViewController
//Property
@property (nonatomic, copy) NSString *myString;
//Outlet
@property (nonatomic, weak) IBOutlet UILabel *myLabel;
@end
之后您可以创建对象并访问它的属性:
ViewController *viewConnection = [[ViewController alloc]init];
viewConnection.myString = @"string";
viewConnection.myLabel.text = @"label text";
//扩展
在您的示例中,您创建了 viewConnection 对象,然后检查它的属性框架:
viewConnection.otherImage.frame
但是您还没有设置它,您还没有设置 otherImage,您还没有设置它的框架,所以这就是您遇到问题的原因。
//扩展 2
它不起作用的原因是因为你试图改变属性的框架(otherImage),我假设它是在你初始化 View Controller 之后的 IBOutlet 但 IBOutlets 是在 View Controller 生命周期的后期创建的,你应该有机会viewDidLoad 或 viewDidAppeare 中的 socket ,但此方法在您呈现/推送 View Controller 后触发。所以你应该创建变量,比方说 CGRect 并在你初始化 View Controller 后设置它的值,然后推送/呈现 View Controller 并在你的类(ViewController)中,例如,在 viewDidLoad 中设置 otherImage.frame = variable。
关于ios - Objective-C 创建一个 ViewController 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22555576/