在iOS中制作滑动视图

时间:2016-02-01 12:45:33

标签: ios swift

我想知道如何创建一排可左右滑动的按钮。例如,在" Cut The Rope"你可以左右滑动找到你想要的盒子。我如何实现这一点,并且以后能够添加更多按钮?

2 个答案:

答案 0 :(得分:0)

您想要实现的滚动效果可以使用UICollectionViewUICollectionView来完成。

如果要使用多个自定义视图实现某种网格,最好使用UIScrollView,因为配置UICollectionView的布局可能非常棘手。

您可以在此处找到有关如何设置UITableView的一些说明:Setting Up a UICollectionView in iOS。 它的API类似于UICollectionViewCells,但它可以水平和垂直滚动。只需在UITableViewCell内添加按钮,就像使用<authentication mode="Forms" /> <authorization> <deny users="?" /> </authorization> 一样。

答案 1 :(得分:0)

您可以使用此代码。

class ViewController: UIViewController {

    @IBOutlet weak var categoryScrollView: UIScrollView!
    var categoryArr = ["Button1","Button2","Button3","Button4","Button5"]
    var buttonColors = [UIColor.greenColor(), UIColor.blueColor(), UIColor.blackColor(), UIColor.cyanColor(), UIColor.magentaColor()]
    let kPadding:CGFloat = 10

    override func viewDidLoad() {
        super.viewDidLoad()

        let buttonSize = CGSizeMake(categoryScrollView.bounds.size.width/2, categoryScrollView.bounds.size.height/2)//hal

        let scrollingView = colorButtonsView(buttonSize, buttonCount: 5)
        categoryScrollView.contentSize = scrollingView.frame.size
        categoryScrollView.addSubview(scrollingView)
        categoryScrollView.showsVerticalScrollIndicator = false
        categoryScrollView.delegate = self
        categoryScrollView.pagingEnabled = true
        categoryScrollView.indicatorStyle = .Default
        categoryScrollView.contentOffset = CGPointMake(0, 0)
    }


    func colorButtonsView(buttonSize:CGSize, buttonCount:Int) -> UIView {
        let buttonView = UIView()
        buttonView.frame.origin = CGPointMake(0,0)
        let padding = CGSizeMake(kPadding, kPadding)
        buttonView.frame.size.width = (buttonSize.width + padding.width) * CGFloat(buttonCount)
        var buttonPosition = CGPointMake(0, padding.height)
        let buttonIncrement = buttonSize.width + padding.width
        for i in 0...(buttonCount - 1)  {
            let button = UIButton(type: .Custom)
            button.frame.size = buttonSize
            button.frame.origin = buttonPosition
            buttonPosition.x = buttonPosition.x + buttonIncrement
            button.setTitle(categoryArr[i], forState: UIControlState.Normal)
            button.backgroundColor = buttonColors[i]
            buttonView.addSubview(button)
        }
        buttonView.backgroundColor = UIColor.redColor()
        return buttonView
    }
}
extension ViewController:UIScrollViewDelegate{
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

        let index = round(scrollView.contentOffset.x / scrollView.frame.size.width)
        print(index)
    }
}