如何同时执行以下代码?

时间:2015-04-28 11:18:59

标签: objective-c for-loop

- (void)test{
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
    [currentBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    currentView.backgroundColor = [UIColor redColor];
    for (UIButton *btn in btnArray) {
        if (btn.tag != currentBtn.tag) {
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        }
    }
    for (UIView *view in viewArray) {
        if (view.tag != currentView.tag) {
            [view setBackgroundColor:[UIColor clearColor]];
        }
    }
} completion:nil];
}

如果仅在一个for循环中执行这两个for循环,我该怎么办?

1 个答案:

答案 0 :(得分:1)

这取决于你的结构。

如果按钮是视图的子视图,那么您可以迭代视图数组,更改背景。然后从中获取子视图(按钮)并设置标题颜色。

[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
    [currentBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    currentView.backgroundColor = [UIColor redColor];
    for (UIView *view in viewArray) {
        if (view.tag != currentView.tag) {
            [view setBackgroundColor:[UIColor clearColor]];
            UIButton *btn = (UIButton *)view.subviews[0];
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        }
    }
} completion:nil];

或者,如果按钮不是子视图或视图,但viewArray和binary中都有相同数量的元素,那么您可以使用for循环并使用循环值来访问每个数组' s元素。

[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
    [currentBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    currentView.backgroundColor = [UIColor redColor];

    for (int i = 0; i < MIN(btnArray.count, viewArray.count); i++) {
        UIButton *btn = btnArray[i];
        if (btn.tag != currentBtn.tag) {
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        }
        UIView *view = viewArray[i];
        if (view.tag != currentView.tag) {
            [view setBackgroundColor:[UIColor clearColor]];
        }
    }
} completion:nil];