我创建MyViewController
并使用for语句索引更改属性
在以下代码中,NSLog
输出case0
,case1
和case2
。
但是,myViewController
始终为redColor
,NSLog
输出first
,first
和first
。
如何更改myVC
中for statement
的属性?
ViewController.m
for (int i = 0; i < 3; i++) {
MyViewController* myVC = [[MyViewController alloc]init];
myVC.view.frame = CGRectMake(0 + _scrollView.frame.size.width * i, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
switch (i) {
case 0:
myVC.state = STATE_FIRST;
NSLog(@"case0");
break;
case 1:
myVC.state = STATE_SECOND;
NSLog(@"case1");
break;
case 2:
myVC.state = STATE_THIRD;
NSLog(@"case2");
break;
default:
break;
}
[_scrollView addSubview:myVC.view];
}
MyViewController.h
typedef enum : NSInteger {
STATE_FIRST = 0,
STATE_SECOND,
STATE_THIRD,
} State;
@property (nonatomic) State state;
MyViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
switch (_state) {
case STATE_FIRST:
self.view.backgroundColor = [UIColor redColor];
NSLog(@"first");
break;
case STATE_SECOND:
self.view.backgroundColor = [UIColor blueColor];
NSLog(@"second");
break;
case STATE_THIRD:
self.view.backgroundColor = [UIColor yellowColor];
NSLog(@"third");
break;
default:
break;
}
}
答案 0 :(得分:1)
问题是您在设置视图控制器的状态之前访问了视图控制器的视图。在switch
语句后设置视图控制器的帧。
for (int i = 0; i < 3; i++) {
MyViewController* myVC = [[MyViewController alloc]init];
switch (i) {
case 0:
myVC.state = STATE_FIRST;
NSLog(@"case0");
break;
case 1:
myVC.state = STATE_SECOND;
NSLog(@"case1");
break;
case 2:
myVC.state = STATE_THIRD;
NSLog(@"case2");
break;
default:
break;
}
myVC.view.frame = CGRectMake(0 + _scrollView.frame.size.width * i, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
[_scrollView addSubview:myVC.view];
}
换句话说,对myVC.view
的调用访问了视图控制器的视图。这反过来导致调用viewDidLoad
。由于在设置状态之前调用了viewDidLoad
,因此即使稍后正确设置了状态,所有视图控制器也都会以红色背景结束。
for
循环迭代结束时被释放。你真的应该对每个视图控制器保持强引用。更好的是,将主视图控制器正确设置为容器视图控制器。请参阅&#34;实现容器视图控制器&#34; UIViewController
的文档部分。
答案 1 :(得分:0)
当您致电myVC.view.frame
时,myVC.view
会致电viewDidLoad
,然后myVC.state
将无法在viewDidLoad
执行代码。您可以设置断点来检查它。
如果要更改状态以更改颜色,可以在MyViewController中覆盖setState
方法,如下所示:
MyViewController.m
- (void)setState:(State)aState
{
_state = aState;
switch (_state) {
case STATE_FIRST:
self.view.backgroundColor = [UIColor redColor];
NSLog(@"first");
break;
case STATE_SECOND:
self.view.backgroundColor = [UIColor blueColor];
NSLog(@"second");
break;
case STATE_THIRD:
self.view.backgroundColor = [UIColor yellowColor];
NSLog(@"third");
break;
default:
break;
}
}