john mike mike john mike mike - 3 months ago 18
iOS Question

Horizontal scroll with buttons in ios?

I have implemented following horizontal scroll with buttons, but it seems like the it start scrolling only after 5 second or like that (it got stuck ,ui is getting blocked i guess).

I have following code to create that in my ViewDidLoad()

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,self.view.frame.size.height-100, self.view.frame.size.width, 100)];

int x = 10;
for (int i = 0; i < 10; i++) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x,10,80,80)];
[button setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
[button setTag:i];
[button setBackgroundColor:[UIColor greenColor]];
[button addTarget:self action:@selector(onClickofFilter:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];

x += button.frame.size.width+10;
}

scrollView.contentSize = CGSizeMake(x, scrollView.frame.size.height);
scrollView.backgroundColor = [UIColor redColor];

[self.view addSubview:scrollView];


check this link for screenshots

enter image description here

Is there any way to make it smooth???pls

Answer

Kindly check this code:

  UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];

  int x = 0;
  CGRect frame;
  for (int i = 0; i < 10; i++) {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    if (i == 0) {
      frame = CGRectMake(10, 10, 80, 80);
    } else {
      frame = CGRectMake((i * 80) + (i*20) + 10, 10, 80, 80);
    }

    button.frame = frame;
    [button setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
    [button setTag:i];
    [button setBackgroundColor:[UIColor greenColor]];
    [button addTarget:self action:@selector(onClickofFilter:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:button];

    if (i == 9) {
      x = CGRectGetMaxX(button.frame);
    }

  }

  scrollView.contentSize = CGSizeMake(x, scrollView.frame.size.height);
  scrollView.backgroundColor = [UIColor redColor];
  [self.view addSubview:scrollView];