如何动态设置滚动视图内容?

时间:2013-08-07 11:12:28

标签: iphone ios ipad

我有一个应用程序,我根据我从数组创建的按钮数量动态设置滚动视图的内容大小。就像这个`

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

    {

        NSMutableDictionary *dicttable=[sarray objectAtIndex:i];

        NSString *head=[dicttable objectForKey:@"cat"];
        btn= [UIButton buttonWithType:UIButtonTypeCustom];
        int j=i+1;
        btn.frame = CGRectMake((j-1)*87,0,87, 44);
        [btn setBackgroundImage:[UIImage imageNamed:@"bar.png"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"bar_hvr.png"] forState:UIControlStateSelected];

        btn.backgroundColor = [UIColor clearColor];

        btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];

        btn.titleLabel.textColor = [UIColor whiteColor];
       [btn setTitle:head forState:UIControlStateNormal];
        btn.tag = i;
        [btn setShowsTouchWhenHighlighted:YES];

            [Scroller addSubview:btn];
                [btn addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

        if(btn.tag==0)
          {
            sendActionsForControlEvents:UIControlEventTouchUpInside];

           }
       else
          {
               btn.selected=NO;



          }


    }

    }


        [Scroller setContentSize:CGSizeMake([sarray count]*85, 44)];

` 但这里的问题是在最后一个按钮后滚动视图滚动。不需要发生,我需要滚动结束视图上的最后一个按钮,任何人都可以帮我这个

3 个答案:

答案 0 :(得分:1)

将scrollview弹跳设置为NO

scrollView.bounces = NO;
是的,因为你说它失去了顺畅。但别无选择。如果您找到任何溶胶,请更新答案。

答案 1 :(得分:0)

嘿,我发送给你完整的例子来制作按钮动态和设置内容大小scrollview的计数,我刚给你一个例子代码你必须设置按钮框的大小为你需要

    UIScrollView *scroll_View=[[UIScrollView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:scroll_View];


int y=0;

for(int i =1;i<10;i++)

{

   // NSMutableDictionary *dicttable=[sarray objectAtIndex:i];

   // NSString *head=[dicttable objectForKey:@"cat"];
   UIButton* btn= [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(y,89,100, 50);
    [btn setBackgroundImage:[UIImage imageNamed:@"bar.png"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"bar_hvr.png"] forState:UIControlStateSelected];

    btn.backgroundColor = [UIColor clearColor];

    btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
    NSString *str=[NSString stringWithFormat:@"%d",i];
    btn.titleLabel.textColor = [UIColor whiteColor];
    [btn setTitle:str forState:UIControlStateNormal];
    btn.tag = i;
    [btn setShowsTouchWhenHighlighted:YES];

    [scroll_View addSubview:btn];
    [btn addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

    y=110*i;

}




   [scroll_View setContentSize:CGSizeMake(y, 400)];

享受编码

答案 2 :(得分:-1)

您只需声明一个CGFloat类型的yMargin变量,并将其初始化为一些必需值为0.现在,每当您垂直添加新子视图时,都会y+=lbl.frame.size.height;

现在setContentSize:CGSizeMake([sarray count]*85, y margin+someRequiredMargin)];

(someRequiredMargin - 你想在下面添加)