如何在IOS的Uiscrollview中反向添加动态元素?

时间:2014-12-01 07:15:41

标签: ios iphone ipad uiscrollview

我的应用程序中有一个带有动态元素的scrollview,我从右到左添加了这样的

if(array.count>0)
    {
          [[cell.contentView viewWithTag:777] removeFromSuperview];

    float x=315.0;
    float width=0.0;
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(70, 52,245,20)];
    scroll.backgroundColor=[UIColor clearColor];
    scroll.tag=777;
    [scroll setContentOffset:CGPointMake(70,245)];
    scroll.showsHorizontalScrollIndicator=NO;

    for(int i =0; i <[array count] ; i++)
    {

        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];

        [btn setBackgroundColor:[UIColor colorWithRed:133.0/255.0 green:155.0/255.0 blue:179.0/255.0 alpha:1.0]];
        btn.layer.cornerRadius = 2;


        [btn setTitle:[[array objectAtIndex:i] objectForKey:@“ggg”] forState:UIControlStateNormal];
        btn.userInteractionEnabled=NO;
        [btn.titleLabel setFont:[UIFont fontWithName:@"Helvetica Neue" size:10.0]];
       CGSize size = [btn.titleLabel.text sizeWithAttributes:
        @{NSFontAttributeName:
              [UIFont fontWithName:@"Helvetica Neue" size:10.0]}];
        x=x-(size.width+10);

        //or whatever font you're using
        [btn setFrame:CGRectMake(x,0,size.width+10,15)];
        [scroll addSubview:btn];
         width=width+x;
         x=x-5;
    }

       scroll.contentSize=CGSizeMake((width+50),20);
        // [scroll setPagingEnabled:YES];
    [cell.contentView addSubview:scroll];

}

这里一切都很好,但是我无法滚动到left.scroll上添加的最后一个元素只允许我从左到右滚动到70.Can任何人都告诉我我哪里出错了此?

2 个答案:

答案 0 :(得分:0)

-(void)addButtonInScrollViewFromArray:(NSArray *)array{
NSInteger arrayCount=array.count;
NSInteger numberIteration=0;
CGFloat buttonXValue=300;
UIScrollView *buttonScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, 360, 60)];
while (numberIteration<arrayCount) {
    UIButton *buttonCreated=[UIButton buttonWithType:UIButtonTypeCustom];
    buttonCreated.frame=CGRectMake(buttonXValue,5, 50, 50);
    buttonXValue-=60;
    [buttonCreated setTitle:[NSString stringWithFormat:@"Button%d",numberIteration] forState:UIControlStateNormal];
    [buttonScrollView addSubview:buttonCreated];
    numberIteration++;
}
CGFloat totalLength=numberIteration*60;
buttonScrollView.contentSize=CGSizeMake(totalLength,60);

}

  

这个函数可以传递数组

答案 1 :(得分:0)

你可以尝试低于一个

scroll.contentSize = CGSizeMake(x+size.width+10,20);