how to make horizontal scrolling menu in iOS

心不动则不痛 提交于 2019-12-20 10:13:56

问题


I would like to make a menu which will have horizontal scrolling.

The menu contains total 16 categories. So I am planning to take 8 on first part and rest 8 on another part.

Can some-one give me insight of what needs to be done?

I believe I need to use below.

UIScrollView
Add buttons in this scrollview

That's it?


What I want is on first screen 8 buttons where first screen will have two rows with 4 buttons set on each row.

Menu sample can be seen at http://www.shoutem.com/


回答1:


If all you're doing is adding buttons to a horizontal scroll view you would do something like follows...

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

        int x = 0;
        for (int i = 0; i < 8; i++) {
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 100, 100)];
            [button setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];

            [scrollView addSubview:button];

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

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

       [self.view addSubview:scrollView];
    }

This will create a scrollview with a height of 100, width as big as its parent, and add 8 buttons to it.




回答2:


You can accomplish you're goal using a UIScrollView and your UIButton objects, it would involve setting each button's frame / layout properties depending on what iOS version you're targeting. (As in Eric's answer).

However, if you're targeting iOS 6 and above, using a UICollectionView where your items/cells are the buttons, then you can get the horizontal scrolling "menu bar" for free. There are plenty of SO posts on this, but the main idea is to use a flow layout where the item size has a height such that there will only be one row of items (just make the item height the same as the collection view's height).

EDIT:

I should say, this might seem like overkill (and maybe it is), but you will end up with a much more flexible component in case requirements change in the future. It also doesn't result in much extra code and abstracts away tedious layout details.



来源:https://stackoverflow.com/questions/18069007/how-to-make-horizontal-scrolling-menu-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!