水平ScrollView有n个按钮:[iOS]

shu*_*hra 2 objective-c uibutton uiscrollview ios

如何在顶部创建一个水平滚动视图,就像一个有很多按钮的滚动菜单(例如:20个按钮)?请帮忙 !

我使用以下代码:

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;
Run Code Online (Sandbox Code Playgroud)

但没有得到我想要的东西.

Sai*_*dra 5

我试图解决这个问题,可能会解决你的问题

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;
Run Code Online (Sandbox Code Playgroud)

截图:

在此输入图像描述

快乐的编码......