【发布时间】:2016-02-01 12:45:32
【问题描述】:
我想知道如何创建一排可以左右滑动的按钮。例如,在“Cut The Rope”中,您可以左右滑动来找到您想要的盒子。我将如何实现这一点,并且以后还能够向其添加更多按钮?
【问题讨论】:
我想知道如何创建一排可以左右滑动的按钮。例如,在“Cut The Rope”中,您可以左右滑动来找到您想要的盒子。我将如何实现这一点,并且以后还能够向其添加更多按钮?
【问题讨论】:
您可以使用此代码。
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)
}
}
【讨论】:
您想要实现的滚动效果可以通过UIScrollView 或UICollectionView 来完成。
如果您想实现具有多个自定义视图的某种网格,最好使用UICollectionView,因为配置UIScrollView 的布局可能非常棘手。
您可以在此处找到有关如何设置UICollectionView 的一些说明:Setting Up a UICollectionView in iOS。
它的 API 类似于UITableView,但它可以水平和垂直滚动。只需在 UICollectionViewCells 中添加按钮,就像使用 UITableViewCell 一样。
【讨论】: