开发者

Dynamically assign views to Scroll View

I have a UIScrollView and five UIViewControllers A,B,C,D,E. The order of the UIViewController views to be shown in the scroll view depends on some pre-requisite (e.g. one day it might be B,A,E,D,C and the next E,A,D,B,C and so on).

How can I keep track of which UIViewController is to be displayed (as in something like tags for each UIViewController which can be stored in an开发者_如何学运维 array and updated)? Is it possible to assign views to the scroll view in the dynamic fashion shown above?


you want to make out a way to permutate the 5 view controllers ? maybe it helps to use the property of prime numbers.

it depends on the count of permutations you want. but since there's only 5 view controllers, there can't be more than 5! = 120 permutations what's good about 5 is that it's a prime number

so if you calculate (n*a) % 5,where a is a constant number from 0 to 4, and n is a variable from 1 to 5 you get a table like this :

a==0,  0,0,0,0,0
a==1,  1,2,3,4,0
a==2,  2,4,1,3,0
a==3,  3,1,4,2,0
a==4,  4,3,2,1,0

as you've seen, that's 5 completely different permutations, in which each number appears exactly once.

so, if you want to have 120 permutations

just apply a const number b (from 0 to 4), and calculate (n*a + b) % 5

then you'll get 5 times the previous result, which is 125 , but there are some repetitions, then the final result will be 120 permutations.

so, the only thing you have to do is to determine a and b with your prerequisite

and apply the following code:

int result = (n*a + b)%5;
static UIView *addedView = nil;
if(addedView != nil)
    [addedView removeFromSuperview];

switch(result)
{
    case 0:
        [self.scrollView addSubview:VCA.view];
        addedView = VCA.view;
        break;
    case 1:
        [self.scrollView addSubview:VCB.view];
        addedView = VCB.view;
        break;

    //and so on...
 }

hope it helps
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜