shubham mishra shubham mishra - 2 months ago 16
Objective-C Question

Horizontal ScrollView having n number of buttons : [iOS]

How to create a horizontal scroll view at the top like a scrolling menu having many buttons (example : 20 buttons) ?
Please help !

I am using following code :

CGRect buttonFrame = CGRectMake(0.0f, 0.0f, scrollView.frame.size.width, scrollView.frame.size.height);
for (NSString *text in wordsArray) {
UIButton *button = [[UIButton alloc]initWithFrame:buttonFrame];
button.text = text;
[scrollView addSubview:button];

buttonFrame.origin.x +=buttonFrame.size.width;
}

CGSize contentSize = scrollView.frame.size;
contentSize.width = buttonFrame.origin.x;
scrollView.contentSize = contentSize;


But not getting what i want.

Answer

I have tried to solve this, might be solve your problem

NSMutableArray *wordsArray = [NSMutableArray arrayWithObjects:@"AAA", @"BBB", @"CCCC", @"dd", @"eeeee", @"ffff", @"g", @"hhh", @"iiiiiii",  @"jjjj", @"kkkkk", @"lllll", nil];

CGFloat btnFrameX = 10.0;
CGFloat Width = self.scrollview.frame.size.width;
CGFloat Height = self.scrollview.frame.size.height;
UIButton *button;
for (NSString *text in wordsArray) {

    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundColor:[UIColor orangeColor]];
    [button.titleLabel setFont:[UIFont systemFontOfSize:20.0f]];
    [button setTitle:text forState:UIControlStateNormal];

    button.frame = CGRectMake(btnFrameX, 20, Width, Height);

    [self.scrollview addSubview:button];

    btnFrameX = btnFrameX + Width + 5;
}

CGSize contentSize = self.scrollview.frame.size;
contentSize.width = wordsArray.count * (Width + btnFrameX);
self.scrollview.contentSize = contentSize;

ScreenShot:

enter image description here

Happy coding...

Comments