ios - Objective-C 创建一个 ViewController 的实例

标签 ios objective-c uiviewcontroller

我想创建一个 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/

相关文章:

ios - 表格 View 单元格中的独特 Collection View ,如 snapchat 故事

objective-c - 命令行 Objective-C 程序如何创建其主 NSThread 线程?

iphone - NSString基础知识-内存-保留-复制

iphone - iphone 支持多少同时(并发)网络连接?

ios - 防止应用程序在运行单元测试时创建 View Controller

ios - 保存 UIViewController 并在需要时再次显示

ios - UIView transitionWithView 不起作用

iphone - 在 iOS 7 上读取 iPhone 的通话记录

ios - 创建具有自动布局约束的 3x3 网格

ios - ImageView放大表行删除第二部分