我有一个简单的应用程序, Storyboard中有两个 View ,两个 segue 将它们连接在一起。在每个 Controller 的 viewDidLoad 中,我以编程方式创建一个按钮,该按钮的操作是切换到另一个 View 。此处显示了其中一个 View Controller 的主要代码。第二个 View Controller 的代码除了 View Controller 和按钮名称外完全相同。
UIButton* button;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (!button) {
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 0, 50, 20);
button.center = CGPointMake(200, 200);
button.titleLabel.font = [UIFont systemFontOfSize:15];
[button setTitle:@"View 2" forState:UIControlStateNormal];
[button setBackgroundColor: [UIColor blueColor]];
[button setTitleColor: [UIColor whiteColor] forState:UIControlStateNormal];
button.tag = 7;
[button addTarget:self action:@selector(view2Action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
} else {
NSLog(@"View 1 already created. Button Tag: %d", button.tag);
}
}
- (void)view2Action:(id)sender {
[self performSegueWithIdentifier:@"Segue2" sender:self];
}
@end
第一个 View 正确显示创建按钮并显示它。单击该按钮会将我带到第二个 View ,并且还会创建并显示相应的按钮。当我单击此按钮时,我会返回到第一个 View 。但是,现在问题是第一个 View 中的按钮不再可见。代码“if (!button)”识别按钮的存在,并打印消息“View 1 already created. Button Tag: 7”。似乎所有按钮属性都在那里,除了它的图形。
有一点,如果我不是在代码中创建按钮,而是将 Storyboard中提供的按钮放置在其中,则不会出现此问题。我需要什么才能使按钮保持显示?
我们将不胜感激。
贝赫扎德
最佳答案
您的 UIButton* button;
变量声明在错误的位置。它在语法上不是非法的,但它在文件和导入该文件的任何内容的全局范围内。从技术上讲,它不是实例变量,因为它不在类的范围内(既不在其 @interface
中,也不在其 @implementation
中)。它应该声明为实例变量或属性。
如果没有看到您的更多代码,我无法完全解释您所看到的行为。作为一个全局变量,它应该仍然可用。但是,也许您的两个 UIViewController 类都访问相同的全局变量,并覆盖按钮属性,而第二个类已窃取它并将其添加到其 View 中(将其从第一个 View Controller 的 View 中删除)。您可以通过记录它的内存地址并查看它在两个实例中是否相同来测试这一点,或者通过测试其 superview
属性并将其与两个 View Controller 的 View 进行比较。
要将其声明为实例变量或属性,它应该位于 @interface/@end
部分或 @implementation/@end
部分内。如果将其声明为属性,则应在其前面加上 @property (...)
。例如:
@implementation ViewController
@property (nonatomic, strong) UIButton *button;
- (void)viewDidLoad {
[super viewDidLoad];
...
...
请注意,这通常在 @interface
中完成,但在 @implementation
中是允许的。
(此答案主要基于@Gellert_Lee 和您自己的评论。)
关于ios - Objective C - 在代码中创建的对象在切换 View Controller 后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42707822/